在woocommerce中,我试图根据客户购买的产品来更改用户角色。我看到了各种代码,并在无法正常工作的情况下尝试了所有代码。
我有几种产品可以检查不同的用户角色更改。
这是我的代码尝试:
add_action('woocommerce_order_status_completed', 'change_role_on_purchase' );
$products_to_check = array( '5345, 5344,5342' );
foreach ( $items as $item ) {
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
$user = new WP_User( $order->user_id );
// Change role
$user->remove_role( 'Subscriber' );
$user->add_role( 'Student-Group' );
// Exit the loop
break;
}
}
$products_to_check = array( '5353, 5352,5351,12119' );
foreach ( $items as $item ) {
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
$user = new WP_User( $order->user_id );
// Change role
$user->remove_role( 'Subscriber' );
$user->add_role( 'Student-11free2' );
// Exit the loop
break;
}
}
$products_to_check = array( '5360, 5359,5358' );
foreach ( $items as $item ) {
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
$user = new WP_User( $order->user_id );
// Change role
$user->remove_role( 'Subscriber' );
$user->add_role( 'Student-11free3' );
// Exit the loop
break;
}
}
$products_to_check = array( '5363, 5362,5361' );
foreach ( $items as $item ) {
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
$user = new WP_User( $order->user_id );
// Change role
$user->remove_role( 'Subscriber' );
$user->add_role( 'Student-11regular2' );
// Exit the loop
break;
}
}
但是它不起作用。任何帮助将不胜感激。
答案 0 :(得分:1)
自Woocommerce 3以来,您的代码已过时且充满错误……请使用以下代码:
add_action('woocommerce_order_status_completed', 'change_user_role_on_order_status_completed', 10, 2 );
function change_user_role_on_order_status_completed( $order_id, $order ){
if ( $order->get_user_id() > 0 ) {
// Here your settings in this multi dimensional array
$user_roles_for_products = array(
'Student-Group' => array( 5345, 5344, 5342 ),
'Student-11free3' => array( 5353, 5352, 5351, 12119 ),
'Student-11free3' => array( 5360, 5359, 5358 ),
'Student-11regular2' => array( 5363, 5362, 5361 ),
);
$user = $order->get_user();
// Loop through order items
foreach ( $order->get_items() as $item ) {
$product_ids = array( $item->get_product_id(), $item->get_variation_id() );
// Loop through all products to check
foreach ( $user_roles_for_products as $role => $products_to_check ) {
if ( array_intersect( $product_ids, $products_to_check ) && in_array( 'Subscriber', $user->roles ) ) {
$user->remove_role( 'Subscriber' );
$user->add_role( $role );
$break = true;
break; // Stop the loop
}
}
if( isset($break) && $break )
break; // Stop the loop
}
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中。应该会更好。