Delete the add to cart button for a specific user role in WooCommerce

In my virtual store using the Divi theme, along with woocommerce, I have two user groups: end users and my resellers, in the case of my end customer, you only need the buy button. Already for my resellers there is only the "add to order" button (provided by the YITH Request A Quote request plugin). If in doubt about how to remove the add to cart button for 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'm trying to use some kind of if to be able to define only a group. Something like that:

 $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 that:

 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 to use 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 display 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

+6
source share
1 answer

The correct code is to do what you want (the user role pool is lowercase, and I use get_userdata(get_current_user_id()) to get the user data.

So, I changed your code a bit:

 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 embed the code in a function that runs with init .

This code is verified and fully functional.

The code goes in the function.php file of your active child theme (or theme). Or also in any php file plugins.

+3
source

Source: https://habr.com/ru/post/1012944/


All Articles