正在尝试使此函数正常工作。第一个可以很好地工作,它获取用户(一直)订购的项目总数,第二个应该根据项目总数更改用户角色。
function get_user_total_purchased_items( $user_id = 0 ){
global $wpdb;
$customer_id = $user_id === 0 ? get_current_user_id() : (int) $user_id;
return (int) $wpdb->get_var( "
SELECT SUM(woim.meta_value)
FROM {$wpdb->prefix}woocommerce_order_items AS woi
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
INNER JOIN {$wpdb->prefix}posts as p ON woi.order_id = p.ID
INNER JOIN {$wpdb->prefix}postmeta as pm ON woi.order_id = pm.post_id
WHERE woi.order_item_type = \'line_item\'
AND p.post_type LIKE \'shop_order\'
AND p.post_status IN (\'wc-completed\')
AND pm.meta_key LIKE \'_customer_user\'
AND pm.meta_value LIKE \'$customer_id\'
AND woim.meta_key LIKE \'_qty\'
" );
}
add_action( \'woocommerce_order_status_completed\', \'change_role_on_purchase\', 20, 2 );
function change_role_on_purchase( $order_id, $order ) {
$user_id = $order->get_customer_id();
$user = new WP_User( $customer_id );
$purchases = get_user_total_purchased_items( $customer_id );
if( $purchases >= 50 && $purchases < 100 && ! in_array( \'bronze_user\', $user->roles ) ) {
// Remove role
$user->remove_role( \'subscriber\' );
// Add role
$user->add_role( \'bronze_user\' );
}
elseif( $purchases >= 100 && $purchases < 200 && ! in_array( \'silver_user\', $user->roles ) ) {
// Remove role
$user->remove_role( \'bronze_user\' );
// Add role
$user->add_role( \'silver_user\' );
}
elseif( $purchases >= 200 && ! in_array( \'gold_user\', $user->roles ) ) {
// Remove role
$user->remove_role( \'silver_user\' );
// Add role
$user->add_role( \'gold_user\' );
}
}
有人知道为什么它不起作用吗?
最合适的回答,由SO网友:jigar041 整理而成
您使用了代码中未定义的错误参数“$customer\\u id”。下面的检查是更新的代码。这应该是工作。用函数替换以下代码
function change_role_on_purchase( $order_id, $order ) {
$user_id = $order->get_customer_id();
$user = new WP_User( $user_id );
$purchases = get_user_total_purchased_items( $user_id );
if( $purchases >= 50 && $purchases < 100 && ! in_array( \'bronze_user\', $user->roles ) ) {
// Remove role
$user->remove_role( \'subscriber\' );
// Add role
$user->add_role( \'bronze_user\' );
}
elseif( $purchases >= 100 && $purchases < 200 && ! in_array( \'silver_user\', $user->roles ) ) {
// Remove role
$user->remove_role( \'bronze_user\' );
// Add role
$user->add_role( \'silver_user\' );
}
elseif( $purchases >= 200 && ! in_array( \'gold_user\', $user->roles ) ) {
// Remove role
$user->remove_role( \'silver_user\' );
// Add role
$user->add_role( \'gold_user\' );
}
}