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

问题描述 投票:1回答:1

在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();
    }
}
php wordpress woocommerce metadata user-data
1个回答
1
投票

而不是保存完整的WC_Product对象,这是一个无法保存为元数据的复杂庞大而繁重的数据平衡,您应该更好地保存产品ID。

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

现在global $woocommerce是不需要的,并且if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {并不是真正需要的(如果你需要,你可以在功能中添加它)。

get_currentuserinfo();也被弃用,也不需要,并被wp_get_current_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_Product对象(来自产品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,具体取决于您要执行的操作。一切都应该有效。

© www.soinside.com 2019 - 2024. All rights reserved.