将当前产品添加到当前登录的用户元数据
Add current product to the current logged in user meta data
在 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_Product
对象,这是一个复杂的庞大而沉重的数据和平,不能保存为元数据,您应该最好保存产品 ID。
为什么?因为产品 ID 只是一个整数(所以非常轻),并且可以让您从保存的产品 ID WC_Product
对象 轻松地 获得。
现在不需要 global $woocommerce
并且 if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
并不是真正需要的 (如果需要,请将其重新添加到函数中)。
另外 get_currentuserinfo();
也已弃用,也不需要并被 wp_get_current_user()
取代。
您最好需要确保当前post ID 是"product" post 类型。所以试试下面的代码:
// 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,具体取决于您要执行的操作。一切正常。
在 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_Product
对象,这是一个复杂的庞大而沉重的数据和平,不能保存为元数据,您应该最好保存产品 ID。
为什么?因为产品 ID 只是一个整数(所以非常轻),并且可以让您从保存的产品 ID WC_Product
对象 轻松地 获得。
现在不需要 global $woocommerce
并且 if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
并不是真正需要的 (如果需要,请将其重新添加到函数中)。
另外 get_currentuserinfo();
也已弃用,也不需要并被 wp_get_current_user()
取代。
您最好需要确保当前post ID 是"product" post 类型。所以试试下面的代码:
// 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,具体取决于您要执行的操作。一切正常。