Answer the question
In order to leave comments, you need to log in
How to change the role of the buyer of a certain product?
Good day!
There was a need to catch the moment of registration when paying through WooCommerce and set a specific role for the user, depending on the product that he bought.
Tell me the necessary hooks and how to implement it better, thanks in advance!
Answer the question
In order to leave comments, you need to log in
It turned out to change the role only in usersmeta, but also success
function s1_change_role( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
if ( $order->user_id > 0 && $product_id == '522' ) {
update_user_meta( $order->user_id, 'paying_customer', 1 );
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'subscriber' );
// Add role
$user->add_role( 'Любитель' );
}
if ( $order->user_id > 0 && $product_id == '527' ) {
update_user_meta( $order->user_id, 'paying_customer', 1 );
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'subscriber' );
// Add role
$user->add_role( 'Клиент' );
}
if ( $order->user_id > 0 && $product_id == '528' ) {
update_user_meta( $order->user_id, 'paying_customer', 1 );
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'subscriber' );
// Add role
$user->add_role( 'VIP-Клиент' );
}
}
}
$current_user_id = get_current_user_id();
$user_info = get_userdata($current_user_id);
$massiv = $user_info->caps;
foreach($massiv as $key => $value)
{
if($key == 'Любитель'){
echo 'Роль пользователя: ';
echo substr($key, 3);
}
if($key == 'Клиент'){
echo 'Роль пользователя: ';
echo substr($key, 3);
}
if($key == 'VIP-Клиент'){
echo 'Роль пользователя: ';
echo substr($key, 3);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question