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

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter chrisbrosnan

    (@cdbrosnan)

    The site in question is Family Traveller

    Thread Starter chrisbrosnan

    (@cdbrosnan)

    I have found the answer elsewhere. The answer is as follows:

    replace 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); 

    with this:

     // 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); 
    • This reply was modified 8 years, 4 months ago by chrisbrosnan.
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Change role and user meta value after purchase of specific product on WooCommerc’ is closed to new replies.