'remove add to cart based on product category and user role
How to disable cart based on a product category and user role? I have 2 functions:
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');
and
add_filter( 'woocommerce_is_purchasable', 'misha_catalog_mode_on_for_category', 10, 2 );
function misha_catalog_mode_on_for_category( $is_purchasable, $product ) {
// First – check product categories
if( has_term( 'uncategorized', 'product_cat', $product->get_id() ) ) {
$is_purchasable = false;
}
// Second – check product tags
if( has_term( 'newyearsale', 'product_tag', $product->get_id() ) ) {
$is_purchasable = false;
}
return $is_purchasable;
}
I tried below and it is not working:
add_filter( 'woocommerce_is_purchasable', 'misha_catalog_mode_on_for_category', 10, 2 );
function misha_catalog_mode_on_for_category( $is_purchasable, $product ) {
// Set Here the user role slug
$targeted_user_role = 'Retailer'; // The slug in "lowercase"
$user_data = get_userdata(get_current_user_id());
// First – check product categories
if( has_term( 'bags', 'product_cat', $product->get_id() ) && 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 );
/*$is_purchasable = false;*/
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
