With the following code I set a cookie:
function cta_setcookie($data) {
//setcookie
setcookie('cta_'.COOKIEHASH, 'checked', time() + 3600, COOKIEPATH);
return $data;
}
and herewith I check if the cookie present:
//check whether user has cookie
$checked = ( !empty($_COOKIE['cta_'.COOKIEHASH]) && 'checked' == $_COOKIE['cta_'.COOKIEHASH] ) ? true : false;
It works, but with this method, the cookie is valid for all sites with my WordPress installation. What I need is to take it only to the actual post.
I tried to add the get_the_ID() function
setcookie('cta_'.COOKIEHASH.get_the_ID(), 'checked', time() + 3600, COOKIEPATH);
to get the cookie unique relative to the post. The cookie is set with the post id, but then the check won´t work. Any attempts failed after adding the get_the_ID(); to change the check :-(
How should the check be coded now?
get_the_ID() isn't available everywhere. You might assign it to a value, then echo that, to be sure that you actually have something to work with.
Like:
$myid = get_the_ID();
echo 'My id is '.$myid;
If that works, then you should be able to concatenate it to your cookie and check for that. IF it's null, then you aren't actually setting the unique value that you are expecting.
Related
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.
I am currently working on a plugin, and I am stuck with an issue.
I executed an SQL request on my database through PhpMyAdmin (which I implemented later through a plugin update mechanism), the request looked like this:
UPDATE `wp_options`
SET `option_value` = replace( `option_value` , 'model', 'ldp_model' )
WHERE `option_name` LIKE 'ldp_container%'
As you can see, I am updating all options value having name beginning by 'ldp_container'. Later in the code execution, when I am retrieving the option value, I am getting a value being false using:
$termId = $term->term_id;
$termMeta = get_option("ldp_container_$termId"); // $termMeta = false
I looked in this issue, and I got to the point where it seems that when I update/create this option, as I used:
update_option("ldp_container_$termID", $termMeta);
instead of
update_option("ldp_container_$termID", $termMeta, false);
The value of this option become part of the alloptions cache. So, retrieving it always return false now, and I do not know how to flush this cache.
Using a plugin update mechanism based on version number, I tried to flush the Wordpress object cache using:
$flush_cache = wp_cache_flush(); // returns true
And the Database query cache too:
$wpdb->flush();
I also tried explicitely deleting those options keys from the cache using a query then looping on results and calling wp_cache_delete:
$result = $wpdb->get_results(
"SELECT 'option_name'
FROM $wpdb->options
WHERE 'option_name' LIKE '%ldp_container_%';"
);
foreach ( $result as $current ) {
wp_cache_delete($current, 'options');
}
Still, no luck.
Does anybody have a clue for me here ?
Thanks,
EDIT:
Seems like my error is somewhere else.
After some debugging using Atom and Xdebug, it points out that the issue is with the unserialize method applied to the string retrieved from the database in the file /wp-includes/option.php as follows:
return apply_filters( 'option_' . $option, maybe_unserialize( $value ) );
maybe_unserialize do that:
if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
return unserialize( $original );
return $original;
The call to the unserialize fails, so it returns false and then the false value is cached...
Using an online unserializer it confirms that the string is not correct, but I do not get why yet.
So, as I assumed my issue was due to the modification in serialized objects I was executing directly on the database. Because of the nature of serialized objects, looking like this:
a:1:{s:9:"ldp_model";s:1651:"{...
The 1651 being the number of characters in the ldp_model string, if you change anything inside this sting, then unserializing using unserialize() will return false, because the actual number of characters is different from the one indicated.
In my case, the solution was to instead of executing a database update of this kind:
$wpdb->query(
"UPDATE $wpdb->options
SET `option_value` = replace( `option_value` , 'ldp_', '' );"
);
To use the Options API as follows:
$result = $wpdb->get_results(
"SELECT `option_name`
FROM $wpdb->options
WHERE `option_name` LIKE '%ldp_container_%';"
);
foreach ( $result as $current ) {
$option = get_option($current->option_name);
if (!empty($option) && !empty($option['ldp_model'])) {
$option['ldp_model'] = str_replace('ldp_', '', $option['ldp_model']);
update_option($current->option_name, $option, false);
}
}
So that the serialized objects stays correct, and the Options API takes care of serialization and unserialization.
Lots of learning here for me ;-)
I have change password at front-end and i m using wp_user_update function,but when user change password it have been log out. the problem is that my old cookies is not updated,so how to update password without log out.have any idea?..
global $wpdb, $current_user;
$user_id = $current_user->ID;
wp_update_user(array('ID'=>$user_id,'user_pass'=>$_POST['user_pass']));
The answer by Aaron Forgue at the WordPress Support is 3 years old, but might be interesting. I had to change the $wpdb->query() to make it work:
global $wpdb;
$profile_id = $_POST['prof_id'];
$username = $_POST['log_name'];
$password = $_POST['wachtwoord'];
$md5password = wp_hash_password($password);
// You may want to use $wpdb->prepare() here. As it stands, malicous code could be passed in via $_POST['prof_id'] or $_POST['log_name']
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->users SET user_pass = %s WHERE ID = %d
",
$md5password,
$profile_id
) );
// Here is the magic:
wp_cache_delete($profile_id, 'users');
wp_cache_delete($username, 'userlogins'); // This might be an issue for how you are doing it. Presumably you'd need to run this for the ORIGINAL user login name, not the new one.
wp_logout();
wp_signon(array('user_login' => $username, 'user_password' => $password));
Credits go to this plugin for the above trick: http://wordpress.org/extend/plugins/change-password-e-mail/
As mentioned by Robahas, make sure that this code is run before headers are sent, else the wp_signon() will not work and the user will be logged out anyway.
i have tried everything i could find to set the user password on registration, but no success... I have the fields showing up, the verification(if the passwords match etc) i print them on screen, i print the userid on screen so every argument needed is there, but the function doesn't seem to work at all...
This doesn't work...
$newpassword = "zzzzzz";
update_user_meta($user_id, 'user_pass', $newpassword);
This doesn't work either...
add_action( 'user_register', 'ts_register_extra_fields', 10 );
function ts_register_extra_fields($user_id, $password='11',$meta = array()){
$userdata = array();
if ( $_POST['password'] !== '' ) {
$userdata['user_pass'] = $_POST['password'];
}
$new_user_id = wp_update_user( $userdata );
}
My customer needs this for tomorrow, so I'm totally lost by now, i have no clue on why it's not working...
Forgot to add, all this code is added in the functions.php of my theme. (It gets into it as i already said that i post the variables on screen).
add_action( 'user_register', 'ts_register_extra_fields', 100 );
function ts_register_extra_fields( $user_id, $password = '', $meta = array() ) {
$userdata = array();
$userdata['ID'] = $user_id;
$userdata['contacto'] = $_POST['contacto'];
$userdata['nif'] = $_POST['nif'];
if ( $_POST['password'] !== '' ) {
$userdata['user_pass'] = $_POST['password'];
echo "im in";
}
$new_user_id = wp_insert_user( $userdata );
echo "id-".$userdata['ID'];
echo "contacto-".$userdata['contacto'];
echo "nif-".$userdata['nif'];
echo "pass-".$userdata['user_pass'];
}
All those echos output the correct data... for example id = 195 the next time i try 196 etc...
contacto and nif show the data that i input in the custom registration field and the pass also shows the data that i had inputed in the custom registration field password...
First of all, I think WordPress is using MD5 encryption for passwords.
$hash = wp_hash_password( $newpassword );
// then wp_update_user with $hash as the user_pass value
Secondly, you shouldn't send passwords in clear text over the Internet. If you can encrypt the password with javascript before you send it, it would probably be a lot safer.
At last, give a shot at updating an existing user by specifying ID in wp_update_user.
A HA! Found the error. I have another plugin installed called "New User Aprovement" which required an administrator aprovement in order for the user to login. That plugin when the administrator accepted the user to login, generated another password (to be able to send the password to the user in a readable mode), invalidating the password update that i made when the user registered(because it generated a random password after the admin accept).
I found this by disabling the plugin and testing the functions.php. It did work. In order to make them both work i just erased the code in the plugin that generated a random password. Although the user doesn't receive the account summary via email. It works for my needs.
Best Regards,
Vcoder
In wordpress, I need to program it such that anytime someone enters or updates a post meta called "start_date", a bit of code is run on what is entered before it is saved.
I need to take what is entered and convert it to a unix timestamp.
Is there a way to do this?
If not, is there a way to add the code on publish or update of the post such that it checks for that meta and updates it if needed?
Assuming you're creating the metaboxes and custom fields with your plugin, you can do the following. Otherwise, it depends on how their saving the data as it could overwrite yours.
Here's something to get you started though depending on what the case is.
add_action('save_post', 'update_the_post_meta', 100, 2);
function update_the_post_meta($post_id, $post) {
if ( defined('DOING_AJAX') && DOING_AJAX ) { return; }
if ( defined('DOING_CRON') && DOING_CRON ) { return; }
if ($post->post_type == 'revision') { return; }
if ( isset($_REQUEST['start_date']) ) :
//do your timestamp code here and save it in $timestamp
add_post_meta($post_id, 'start_date', $timestamp, true) or update_post_meta($post_id, 'start_date', $timestamp);
else :
delete_post_meta($post_id, 'start_date');
endif;
}
Right now the priority of the add_action is set to 100 (the higher the number, the less priority it has). So, if you're trying to override someone else's function, you may need to increase the priority number. Also, this is assuming the name of the input field is "start_date".