在WooCommerce产品页面中,我试图将当前产品添加为新的用户元数据。我这样做正确吗?
那我该如何在购物车页面中检索此产品元数据?
// 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();
}
}
答案 0 :(得分:1)
与其保存完整的WC_Product
对象(这是一个复杂而又庞大的数据,无法保存为元数据),您应该更好地保存产品ID 。
为什么?因为产品ID只是一个整数(所以很轻),并且可以让您从保存的产品ID中轻松获取{1}对象。
现在不需要WC_Product
,而实际上并不需要global $woocommerce
(如果需要,您可以将其添加回函数中)。
也已弃用if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
,也不再需要get_currentuserinfo();
。
您最好需要确保当前帖子ID是“产品”帖子类型。因此,请尝试以下代码:
wp_get_current_user()
现在要检索此自定义用户元数据和WC_Product对象(来自产品ID),您将使用:
// 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();
}
在购物车页面中,您可能只需要产品ID,具体取决于您要执行的操作。一切都会正常工作。