Php 将当前产品添加到当前登录的用户元数据

Php 将当前产品添加到当前登录的用户元数据,php,wordpress,woocommerce,metadata,user-data,Php,Wordpress,Woocommerce,Metadata,User Data,在WooCommerce产品页面中,我尝试将当前产品添加为新用户元数据。我这样做对吗 那么我如何在购物车页面中检索此产品元数据 // save for later public function save_for_later(){ if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { global $woocommerce; // get user details global $c

在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();
    }
}

与其保存完整的
WC_产品
对象,这是一个复杂的庞大数据,无法保存为元数据,不如保存产品ID

为什么??因为产品ID只是一个整数(因此非常轻),并且允许您从保存的产品ID轻松地获取
WC_产品
Object

现在不需要
global$woocommerce
,并且
if(已定义('DOING_AJAX')&&DOING_AJAX){
实际上不是必需的(如果需要,您可以将其设置回函数中添加)

另外,
get\u currentuserinfo();
也被弃用,不再需要,并被
wp\u get\u current\u user()
取代

您最好确保当前帖子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();
}
现在要检索此自定义用户元数据和WC_产品对象(从产品ID),您将使用:

$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 );
在购物车页面中,您可能只需要产品ID,这取决于您尝试执行的操作。一切都应该正常