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



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

  • 如果用户购买了项目a,则会分配user-role-a
  • 如果用户购买了Item-B,则会分配user-role-B
  • 如果用户购买了项目B中的2个或多个,则还分配了用户权限c

因此可以分配多个用户角色。基于购买产品后更改用户角色,这是我的尝试:

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

最新更新