Home > OS >  Restrict certain user roles from making purchases in Woocommerce
Restrict certain user roles from making purchases in Woocommerce

Time:08-07

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;
}

CodePudding user response:

The following code will restrict the ability to purchase products based on user role. The user roles cliente_empresa_limited, cliente_modo_catlogo, and administrator will be able to purchase without restriction:

/* Restrict the ability to buy products based on the user role.
   Roles 'cliente_empresa_limited', 'cliente_modo_catlogo',
   and 'administrator' will be able to purchase */

function modo_catalogo_por_rol_usuario(){

$user = wp_get_current_user();
$user_meta=get_userdata( $user->ID );
$user_roles=$user_meta->roles;

    if ( ( in_array( 'cliente_empresa_limited', (array) $user_roles ) ) || ( in_array( 'cliente_modo_catlogo', (array) $user_roles ) ) || ( in_array( 'administrator', (array) $user_roles ) ) ) {
        return true;
    }
    else {
        return false;
    }
}
add_filter( 'woocommerce_is_purchasable', 'modo_catalogo_por_rol_usuario' );

Add the code above in functions.php file of your active child theme or active theme. It is tested and it works.

CodePudding user response:

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.

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;

    if ( 0 < count( array_intersect( $catalog_roles, $roles ) ) ) {
        $is_purchasable = false;
    }

    return $is_purchasable;
}
  • Related