Wordpress OOP Framework not working with update_options function - wordpress

I'm trying to get update_options to work with this function. Basically, the user enters an activation code and submits it through the plugin options page. The code is sent to the third party and the status returned if successful. This all works as it should but I can't get update_options to change the status of the option in question.
Here is the update function (part of an OOP framework I'm using):
private function _admin_options_update() {
// Verify submission for processing using wp_nonce
if( wp_verify_nonce( $_REQUEST['_wpnonce'], "{$this->namespace}-update-options" ) ) {
$data = array();
/**
* Loop through each POSTed value and sanitize it to protect against malicious code. Please
* note that rich text (or full HTML fields) should not be processed by this function and
* dealt with directly.
*/
foreach( $_POST['data'] as $key => $val ) {
$data[$key] = $this->_sanitize( $val );
}
/**
* Place your options processing and storage code here
*/
// Update the options value with the data submitted
update_option( $this->option_name, $data );
// Redirect back to the options page with the message flag to show the saved message
wp_safe_redirect( $_REQUEST['_wp_http_referer'] . '&update=1' );
exit;
}
}
I'm trying to run this function:
update_option( $WPBackitup->options['status'], $license_data->license );

Figured this one out myself. Basically, the framework was sanitizing any data submitted via its form variables and then submitting it to the DB. I got the third party API to work by manually loading its return into the array that the framework sanitized and sent to the DB. Once I'd done that, update_options() worked like a charm!

Related

Wordpress function cannot call submit_button() as it ends with "undefinied function"

i am a real very newbie in coding and in Wordpress. Trying my first test plugin to understand basics. I am able to define plugin, register it, so I can see it in plugins, activate it.
My later goal is to be able to create custom form, save user-specific data to new DB table, and then enable reading/editing it.
I tried to follow the instructions from gmazzap placed here: https://wordpress.stackexchange.com/questions/113936/simple-form-that-saves-to-database
I just am having following error from WP in time of trying to display preview of new screen having a shortcode [userform] in it:
*Fatal error: Uncaught Error: Call to undefined function submit_button() in /data/web/virtuals/131178/virtual/www/subdom/test/system/wp-content/themes/twentytwentythree-child/functions.php:14
*
My functions.php of my theme now looks like this:
<?php
add_action('init', function() {
add_shortcode('userform', 'print_user_form');
});
function print_user_form() {
echo '<form method="POST">';
wp_nonce_field('user_info', 'user_info_nonce', true, true);
?>
All your form inputs (name, email, phone) goes here.
<?php
submit_button('Send Data');
echo '</form>';
}
add_action('template_redirect', function() {
if ( ( is_single() || is_page() ) &&
isset($_POST['user_info_nonce']) &&
wp_verify_nonce($_POST['user_info_nonce'], 'user_info')
) {
// you should do the validation before save data in db.
// I will not write the validation function, is out of scope of this answer
$pass_validation = validate_user_data($_POST);
if ( $pass_validation ) {
$data = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone'],
);
global $wpdb;
// if you have followed my suggestion to name your table using wordpress prefix
$table_name = $wpdb->prefix . 'my_custom_table';
// next line will insert the data
$wpdb->insert($table_name, $data, '%s');
// if you want to retrieve the ID value for the just inserted row use
$rowid = $wpdb->insert_id;
// after we insert we have to redirect user
// I sugest you to cretae another page and title it "Thank You"
// if you do so:
$redirect_page = get_page_by_title('Thank You') ? : get_queried_object();
// previous line if page titled 'Thank You' is not found set the current page
// as the redirection page. Next line get the url of redirect page:
$redirect_url = get_permalink( $redirect_page );
// now redirect
wp_safe_redirect( $redirect_url );
// and stop php
exit();
}
}
});
Note: I have not got to DB exercise, point of my question is submit_button.
As indicated in the error, the code on line 1 points to non identified function:
submit_button('Send Data');
I understood from other discussions submit_button should be core function of WP, so I should be able to call it "directly", without the need of a definition.
I tried following:
originally had very similar code within the plugin, moved to functions.php
reinstalled core of WordPress version 6.1.1
tried several different Themes (as it looked this worked for other users, I tried "classic" and "twentytwentythree" )
And still no little step further, still having same issue with error described above. What I am doing wrong?
If someone would confirm this is WP core installation issue, I am ready to reinstall WP from scratch, just trying to save some time, if there might be other cause.
Thank you for any suggestions.

WooCommerce Eway plugin not creating customer token for new customer

I have setup a fresh docker container with Wordpress 5.0.3 and the latest WC and WC Eway plugin (WooCommerce eWAY Gateway).
Created a store with some products, hooked up my Eway sandbox environment, enabled Save Cards (which would enable the token) and created an order.
After checking the post_meta in my DB for the order, I didn't see a _eway_token_customer_id field. While being logged in as a customer, I tried again and with the new order I still do not get a token.
The reason for this tests is that I got this strange behaviour in my real, new website, where the first order with a NEW customer, doesn't result in a token.
However, when I create a second order whilst being logged in, I do get a _eway_token_customer_id value within the order_meta.
It is imperative for me to get that token with the first order, because after that I will auto renew the product using the tokenp ayment option.
Debugging this issue is hell, and I find it very disconcerting that on my fresh WP installation I get no token at all.
Is there anyone that has a bright idea?
**update
After some digging around in the Eway Plugin, I found out that the first time I do an order, the function request_access_code() from the class WC_Gateway_EWAY is checking if there is a token in the database for this user.
The function body:
protected function request_access_code( $order ) {
$token_payment = $this->get_token_customer_id( $order );
if ( $token_payment && 'new' === $token_payment ) {
$result = json_decode( $this->get_api()->request_access_code( $order, 'TokenPayment', 'Recurring' ) );
} elseif ( 0 === $order->get_total() && 'shop_subscription' === ( version_compare( WC_VERSION, '3.0', '<' ) ? $order->order_type : $order->get_type() ) ) {
$result = json_decode( $this->get_api()->request_access_code( $order, 'CreateTokenCustomer', 'Recurring' ) );
} else {
$result = json_decode( $this->get_api()->request_access_code( $order ) );
}
if ( isset( $result->Errors ) && ! is_null( $result->Errors ) ) {
throw new Exception( $this->response_message_lookup( $result->Errors ) );
}
return $result;
}
The function handles three possible outcomes:
1) new customer: results in calling `$this->get_api()->request_access_code( $order, 'TokenPayment', 'Recurring' )` <-- this is the one we are after!
2) shop_subscription: calls `$this->get_api()->request_access_code( $order, 'CreateTokenCustomer', 'Recurring' )`
3) else..: calls `$this->get_api()->request_access_code( $order )`
What is happening during debugging, is that the $token_payment variable has the value of an empty string for a new customer, instead of new.
So I will attempt to fix this, either via a filter/action hook, or figure out why this is happening.
When I forced the function the always use the first if block, I got my token. :)
**Update 2:
I tested with an existing user account, created a new order.
When I look in the post_meta table:
Voila, the new value is present.
However, when I am not logged in and I create an account, the new value is not added and that is where it goes wrong.
A temp fix would be to use a hook and add the new value to the order so that when get_token_customer_id is called it retrieves a new value and not an empty string.
I think this is a bug, since this value should be added. It explains why the second transactions get the token but not the first.
If only Woocommerce Eway plugin had a git repo.... I could flag an issue or fork it.
***Solution without hack
Added this to my plugin (or functions.php if you like):
add_action( 'woocommerce_checkout_order_processed', function( $order_id, $posted_data, $order ) {
update_post_meta( $order_id, '_eway_token_customer_id', 'new' );
}, 10, 3);
This will add the new value when you checkout with a non-existent user.
The token was added nicely after adding my creditcard details.
The matter of the fact stays that the plugin still has a bug, which you can work around.

A Webhook contact form for Discord in wordpress

So I'll start out by saying, that I am a bit new to this.
So I have this website I'm currently making. It's a guild website for World of Warcraft, and we want to be able to have new people being able to apply for membership.
Making the contact form is easy enough through plugins, but this is in theory what I wish to make:
A contact form where when filled in, the application form will push a notification to a webhook set in Discord where when new applicants happen, a message in a channel will be made, notifying the leaders about it.
Do I need to create a plugin myself, or is there any plugin that can offer this functionality?
I had the same needs, after sometime i found a way to do it.
Its actually very simple with WPForms.
WPForms has hooks so you can easily track forms submitions with the wpforms_process_complete hook. This hook allows you to track ALL WPForms sumbission. But maybe you'd like to have different forms. If you wish to track only a specific form, you can add the form id to the end of the hook name.
In my case i had many different forms which are being handled in various different ways, so i had to split them. When a form is being created in WPForms, it receives an ID so does the fields of the named form.
In my case after my form was created it had the following id :
The hook function.
As explained on the Discord Webhook page, Webhooks are a low-effort way to post messages to channels in Discord. They do not require a bot user or authentication to use. The endpoint supports both JSON and form data bodies. In my case i went for JSON.
As explained here you just need to use one of the the content file or embeds field. On this example i will just send a message, so i'll be using the content field.
Once the above instructions applied, you should end up with something close to the following function :
if ( ! function_exists( 'discord_form_submission' ) ) :
/**
* This will fire at the very end of a (successful) form entry.
*
* #link https://wpforms.com/developers/wpforms_process_complete/
*
* #param array $fields Sanitized entry field values/properties.
* #param array $entry Original $_POST global.
* #param array $form_data Form data and settings.
* #param int $entry_id Entry ID. Will return 0 if entry storage is disabled or using WPForms Lite.
*/
function discord_form_submission( $fields, $entry, $form_data, $entry_id )
{
// You have to replace this url by your discord webhook.
$endpoint = 'https://discord.com/api/webhooks/{webhook.id}/{webhook.token}';
// This is the content you can put anything you wish.
// In my case i needed the Name, Class, and the Level of the players.
$content = "**Name :** " . $fields[1]['value'] . PHP_EOL;
$content .= "**Class :** " . $fields[2]['value'] . PHP_EOL;
$content .= "**Level :** " . $fields[3]['value'] . PHP_EOL;
// WP has its own tool to send remote POST request, better use it.
wp_remote_post( $endpoint , [
'headers' => [
'Content-Type' => 'application/json; charset=utf-8'
],
'body' => wp_json_encode([ // Same for the JSON encode.
'content' => $content,
]),
'method' => 'POST',
'data_format' => 'body'
]);
}
endif;
This function must be added in the functions.php file of your theme.
Last but not least, with the help of the WP add_action Function you need to hook up with the wpforms_process_complete hook. In my case since i want to only hook up to the form with the id 1862 i have added the id at the end of the hook which gives us the following code :
add_action( 'wpforms_process_complete_1862', 'discord_form_submission', 10, 4 );
This code must be added in the functions.php file of your theme after our newly added function.

check if user email exists, and if not, stop the submit of the ninja form

I've one form built with ninja forms, and I use ajax to send it.
I need to check if the email introduced already exists in database (user_email), and if it exists properly, I send the form properly, but if it doesn't exist, the form isn't submitted, and I need to give the user the message like "email does not exist".
The form is a survey to be completed by a registered user, who gives us a feedback about our services, but the survey is located in a page where the user can send its opinion without needed to be logged.
I'm investigating, and at the moment I have:
function example_disable_saving_subs( $save, $form_id ) {
global $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
$email = ninja_forms_get_field_by_id( 18 );
//cuestionario feedback profesor sobre creación de un curso
if($form_id == 3){
if( !email_exists( $email )) {
$save = false;
$ninja_forms_processing->add_error('email_no_existe', 'El email no existe');
}
}
return $save;
}
add_filter( 'ninja_forms_save_submission', 'example_disable_saving_subs', 2, 10 );
But I pick up the field $email without value introduced...In addition, I don't know the way to give the user the message "email does not exists".
As you see, I chose the filter ninja_forms_save_submission. Maybe this is not the correct filter.
I hope your valious help.
Thanks in advance, Daniel
thanks for your help #Renato , I give you +1 :)
It's true that I can do it through the way you tell me, but I don't want to break the api of WordPress, that is, the way this cms uses javascript, php, etc etc...So, I wanted to do this through the API of ninja forms, which is the plugin I use for build this survey.
Finally, I solved it...it was my mistake, because I didn't use the correct filter...Investigating few more, there's another filter much more appropiate: ninja_forms_pre_process
Here is the code:
function add_change_ninja_forms_landing_page(){
add_action( 'ninja_forms_pre_process', 'handle_custom_ninja_forms' );
}
add_action( 'init', 'add_change_ninja_forms_landing_page' );
function handle_custom_ninja_forms(){
global $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
//if it's my form of survey
if( $form_id == 3 ){
$email = $ninja_forms_processing->get_field_value( 18 ); //pick up the value of the email field
//use the native function of wordpress to check if there's a user with this email
//is anyone has this email, it does not exist
if( !email_exists( $email )) {
$ninja_forms_processing->add_error('email_no_existe', 'El email indicado no está registrado en nuestra base de datos'); //add_error stop the form and gives the error message
}
}
}
With the code above everything works fine! :)
Thanks!
Daniel,
I am not familiar with ninja_forms, but thinking of javascript, you can encapsulate your code to verify if users exists into an url and then, when making the ajax call, use it to verify...
If you can't change the ajax request, you can validate the field on it's blur event and disable the submit button untill it's marked as "successfull"
For you to create PHP files, and yet, use all Wordpress power and functionalities, you can simply include this file on the beggining of the file that will be called
require(wp-blog-header.php)

wp_mail() filter wp_mail_from not working

I built a small function to send contact form results and bug reports.
I ask the user to enter name and email and I want to use that email address to appear in mail I'm getting.
I'm using the wp_mail filter for this:
add_filter( 'wp_mail_from', 'my_mail_from', $gotten_mail );
function my_mail_from( $email )
{
return $email;
}
It's not working.
I'm thinking maybe to change smtp address instead of using this filter.
searching how.
Can you please help me?
Thanks in advance.
Realize this is over a month old, but here goes...
You can't add your custom parameters into your add_filter call that way. Instead, you will need to grab the entered email in your callback function, like so:
add_filter( 'wp_mail_from', 'custom_slug_mail_from' );
/**
* Function to change mail_from to input entered via form.
*/
function custom_slug_mail_from( $email ) {
/**
* Use the user-submitted email if present.
*/
if ( isset( $_REQUEST[ 'email_from_form' ] ) )
return sanitize_email( $_REQUEST[ 'email_from_form' ] );
return $email; // if no email submitted, use default.
}
Haven't tested this, but I think it should work. Be sure to change 'custom_slug' to the name of your theme or plugin folder per the WordPress Theme Guidelines and change 'email_from_form' to be the name of the input field from your form.
P.S. You'll get WordPress-related answers faster at wordpress.stackexchange.com

Resources