phpwordpresswoocommerceuser-rolesproduct-variations

Disable multiple product variations conditionally based on user role in WooCommerce


I have product variations for attribute "Lizenz" with 3 values:

Also 3 corresponding user roles like:

Partly based on Hide specific WooCommerce Product Variations from User Role based on a custom field.

//get userrole
function is_user_role( $role ) {
    global $current_user;
    return in_array( $role, $current_user->roles );
}

The code works if I define only 1 variation to be hidden, but not if I add another one with "and" (&&)

// Hide variation based on user role
add_filter( 'woocommerce_variation_is_visible', 'hide_conditionally_product_variation', 10, 4 );
function hide_conditionally_product_variation( $is_visible, $variation_id, $product_id, $variation ) {

// check if userole is "pro" and then hide the variations "pro" and "mini"
    if ( is_user_role('pro') && 'mini' && 'bussines' === strtolower( $variation->get_attribute( 'pa_lizenz' ) ) )

    {
        return false;
    }
    return $is_visible;
}

Solution

  • First you can replace is_user_role() function with newly wc_current_user_has_role() WooCommerce dedicated function.

    Then, you better need to check if each user role has not the correct Lizenz attribute value as following:

    // Hide variation based on user role
    add_filter( 'woocommerce_variation_is_visible', 'hide_conditionally_product_variation', 10, 4 );
    function hide_conditionally_product_variation( $is_visible, $variation_id, $product_id, $variation ) {
    
        $license = strtolower( $variation->get_attribute( 'pa_lizenz' ) );
    
        if ( ( wc_current_user_has_role('mini')     && $license !== 'mini' )
          || ( wc_current_user_has_role('pro')      && $license !== 'pro' )
          || ( wc_current_user_has_role('business') && $license !== 'business' ) ) 
        {
            return false;
        }
        return $is_visible;
    }
    

    It should work now for each user role as expected, hidding variations that have not the correct corresponding Lizenz attribute value.