[英]Change user role depending on purchased products in WooCommerce
在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;
}
}
但這是行不通的。 任何幫助將不勝感激。
由於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文件中。 它應該更好地工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.