简体   繁体   English

在WooCommerce购买特定产品后,是否更改角色和用户元价值?

[英]Change role and user meta value after purchase of specific product on WooCommerce?

On our WooCommerce store we have a specific product that when purchased and the order confirmed changes the user role to a 'club' member (premium membership). 在我们的WooCommerce商店中,我们有一种特定的产品,该产品在购买并确认订单后会将用户角色更改为“俱乐部”会员(高级会员)。

We also need to now assign a unique member ID to the user which I am attempting to assign through copying the number from the order ID. 现在,我们还需要通过复制订单ID中的号码为我试图分配的用户分配一个唯一的会员ID。 The meta key 'club_member_id' has been added as a custom field for users with a current default value of 1, through the Advanced Custom Fields plugin. 通过高级自定义字段插件,已将元键'club_member_id'添加为当前默认值为1的用户的自定义字段。

The source code below is changing the user role to 'club' but does not change the meta value for 'club_member_id'. 下面的源代码将用户角色更改为“ club”,但未更改“ club_member_id”的元值。 Can anybody shed some light on this? 有人能对此有所启示吗?

//Change role and add Club ID if club membership is bought

function lgbk_add_member( $order_id ) {

$order = new WC_Order( $order_id );
$items = $order->get_items();

foreach ( $items as $item ) {

    $product_name = $item['name'];
    $product_id = $item['product_id'];
    $product_variation_id = $item['variation_id'];
    $original_cid = get_user_meta('club_member_id');
    $meta_key = 'club_member_id';
    $meta_value = $order_id;

if ( $order->user_id > 0 && $product_id == '7968' ) {

    update_user_meta( $order->user_id, 'paying_customer', 1 );
    $user = new WP_User( $order->user_id );
    // Remove role
    $user->remove_role( 'customer' );
    // Add role
    $user->add_role( 'club' );
    // Remove club member ID
    $user->delete_user_meta($user, $meta_key);
    // Add club member ID
    $user->add_user_meta($user, $meta_key, $meta_value);

    } 

  }

} add_action( 'woocommerce_order_status_completed', 'lgbk_add_member' );

This code has been placed in our theme's functions.php file. 该代码已放置在我们主题的functions.php文件中。 Thanks in advance. 提前致谢。

Instead of this : 代替这个:

 // Remove club member ID
 $user->delete_user_meta($user, $meta_key);
 // Add club member ID
 $user->add_user_meta($user, $meta_key, $meta_value);

I will do it like that : 我会那样做:

// Remove club member ID
delete_user_meta($order->user_id, $meta_key);
// Add club member ID
add_user_meta( $order->user_id, $meta_key, $meta_value);

add_user_meta and delete_user_meta are simple WordPress functions which will return false on failure and the primary key id on success, they are not listed in the public method for WP_User class. add_user_metadelete_user_meta是简单的WordPress函数,如果失败,将返回false,如果成功,将返回主键ID,但未在WP_User类的公共方法中列出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM