简体   繁体   中英

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).

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. 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.

The source code below is changing the user role to 'club' but does not change the meta value for '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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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