79094812

Date: 2024-10-16 15:45:57
Score: 1
Natty:
Report link

Bit of a change to @jjj answer above. But I needed it to work with a certain product only if the user had "user_a" role:

function change_role_on_purchase( $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'];

        if( current_user_can( 'role_a' ) ){

        if ( $order->user_id > 0 && $product_id == '248' ) {
            update_user_meta( $order->user_id, 'paying_customer', 1 );
            $user = new WP_User( $order->user_id );

            // Remove role
            $user->remove_role( 'role_a' ); 

            // Add role
            $user->add_role( 'role_b' );
        }
    }
    else {
        return true;
    }

    }
}

add_action( 'woocommerce_order_status_processing', 'change_role_on_purchase' );
Reasons:
  • Blacklisted phrase (0.5): I need
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @jjj
  • Low reputation (0.5):
Posted by: Adam OXenham Smith