No matter how many ways I try, I can’t get it to work. I must mention that I have used this snippet for other purposes, such as restricting the possibility of buying if the product contains a certain tag or a certain category.
But to do this based on the user role, I just haven’t been able to pull it off. I remember this did work like a couple of months ago, but now, it just doesn’t work anymore. Is there something I’m missing?
add_filter('woocommerce_is_purchasable', 'modo_catalogo_por_rol_usuario', 10, 2 );
function modo_catalogo_por_rol_usuario( $is_purchasable, $product ) {
$user = wp_get_current_user();
$catalog_roles = array('cliente_empresa_limited', 'cliente_modo_catlogo', 'administrator'); //add your user roles here
$roles = ( array ) $user->roles;
$is_purchasable = true;
if ( in_array( $catalog_roles, $roles ) ) {
$is_purchasable = false;
}
return $is_purchasable;
}
2
Answers
The following code will restrict the ability to purchase products based on user role. The user roles
cliente_empresa_limited
,cliente_modo_catlogo
, andadministrator
will be able to purchase without restriction:Add the code above in
functions.php
file of your active child theme or active theme. It is tested and it works.You should use
array_intersect
which will return an array of matches between two arrays. If the count is greater than 0, then it will be true.