当 WooCommerce 订单状态完成时,根据产品 ID 和数量添加用户角色

Add user role(s) based on product IDs and quantity when WooCommerce order status is completed

我正在尝试根据几个不同的标准分配用户角色:

因此可以分配多个用户角色。基于Change User Role After Purchasing Product,这是我的尝试:

add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );

function wpglorify_change_role_on_purchase( $order_id ) {

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

// CHILD PRODUCT MAKES PRIMARY ADULT ROLE
    
    $product_id = 50; // that's the child product ID

    foreach ( $items as $item ) {

        if( $product_id == $item['product_id'] && $order->user_id ) {
            $user = new WP_User( $order->user_id );

            // Add new role
            $user->add_role( 'primary-adult' );
        }
    }

// ADULT PRODUCT MAKES ADULT ROLE
    
    $product_id = 43; // that's the adult product ID
    
    foreach ( $items as $item ) {

        if( $product_id == $item['product_id'] && $order->user_id ) {
            $user = new WP_User( $order->user_id );

            // Add new role
            $user->add_role( 'adult' );
        }
    }   
    
}

通过我的代码,我获得了一些解决方案(根据购买的产品 ID 分配角色),但我仍然需要能够根据购买的商品数量分配角色。有什么建议吗?

除了回答你的问题,我还对你的代码做了一些修改和优化:

  • 无需按条件再次检查订单商品,而是将条件放入循环中
  • $item->get_quantity()可以用来知道数量
  • 可以根据产品 ID 将多个角色分配给同一用户

所以你得到:

function action_woocommerce_order_status_completed( $order_id, $order ) {
    // Product IDs
    $item_a = 30;
    $item_b = 813;

    // Is a order
    if ( is_a( $order, 'WC_Order' ) ) {
        // Get user
        $user = $order->get_user();

        // User is NOT empty
        if ( ! empty ( $user ) ) {
            // Loop through order items
            foreach ( $order->get_items() as $key => $item ) {
                // Item A
                if ( $item->get_product_id() == $item_a ) {
                    // Add user role
                    $user->add_role( 'user-role-a' );
                // Item B
                } elseif ( $item->get_product_id() == $item_b ) {
                    // Add user role
                    $user->add_role( 'user-role-b' );

                    // Quantity equal to or greater than
                    if ( $item->get_quantity() >= 2 ) {
                        // Add user role
                        $user->add_role( 'user-role-c' );                       
                    }
                }
            }
        }
    }
}
add_action( 'woocommerce_order_status_completed', 'action_woocommerce_order_status_completed', 10, 2 );