Reputation: 61
In my virtual store using the Divi theme along with woocommerce I have the two groups of users: end users and my resellers, in the case of my end client would need only appear the “buy” button. Already for my resellers only the “add to order” button (provided by the YITH Request A Quote plugin). In case the doubt would be on how to remove the add to cart button for the reseller accounts, I know using the code:
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
I remove the button from the whole site, but I am trying to use some kind of if
to be able to only define a group.
Something like this:
$user = wp_get_current_user();
if ( in_array( 'Revenda', (array) $user->roles ) ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}
or this:
if( current_user_can('revenda') ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}
I am also trying this code:
function user_filter_addtocart_for_shop_page(){
$user_role = get_user_role();
$role_id = get_role('Revenda');
if($user_role == $role_id){
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
}
}
Where get_user_role will be displaying from:
function get_user_role() {
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
return $user_role;
}
How can I achieve this?
Thanks
Upvotes: 6
Views: 2701
Reputation: 253784
The correct code to do what you want to (The user role slug is in lower case and I use get_userdata(get_current_user_id())
to get the user data.
So I have changed a little bit your code:
function remove_add_to_cart_for_user_role(){
// Set Here the user role slug
$targeted_user_role = 'revenda'; // The slug in "lowercase"
$user_data = get_userdata(get_current_user_id());
if ( in_array( $targeted_user_role, $user_data->roles ) ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}
}
add_action('init', 'remove_add_to_cart_for_user_role');
I have embed the code in a function that is fired on init
hook.
This code is tested and fully functional.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Upvotes: 4