Reputation: 129
In WooCommerce product page, I'm trying to add the current product as a new user meta data. Am I doing this right?
Then how can I retrieve this product meta data in cart page?
// save for later
public function save_for_later(){
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
global $woocommerce;
// get user details
global $current_user;
get_currentuserinfo();
$product = wc_get_product( get_the_ID() );;
if (is_user_logged_in())
{
$user_id = $current_user->ID;
$meta_key = 'product';
$meta_value = $product;
update_user_meta( $user_id, $meta_key, $meta_value);
}
exit();
}
}
Upvotes: 1
Views: 375
Reputation: 254362
Instead of saving the complete WC_Product
Object, Which is a complex huge and heavy peace of data that can not be saved as meta data, you should just better save the product ID.
Why? Because the product ID is just an integer (so something very light) and will allow you to get the WC_Product
Object easily from the saved product ID.
Now global $woocommerce
is unneeded and if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
is not really required (If it's needed you set add it back in the function).
Also get_currentuserinfo();
is deprecated, unneeded too and replaced by wp_get_current_user()
.
You should better need to be sure that the current post ID is a "product" post type. So try the following code instead:
// save for later
public function save_for_later(){
global $post;
// Check that the current post ID is a product ID and that current user is logged in
if ( is_user_logged_in() && is_a($post, 'WP_Post') && get_post_type() === 'product' ) {
update_user_meta( get_current_user_id(), 'product_id', get_the_id());
}
exit();
}
Now to retrieve this custom user meta data and the WC_Product Object (from the product ID), you will use:
$product_id = get_user_meta( get_current_user_id(), 'product_id', true );
// Get an instance of the WC_Product object from the product ID
$product = wc_get_product( $product_id );
In cart page, you might just need the product ID, depending on what you are trying to do. Everything should work.
Upvotes: 1