skip to Main Content

I have a woocommerce store that sells variable products.

e.g Blowgun
variable:
single item
box of 4

Im trying to make it so variable products will not show the single item when logged in.
Ive got it to a point where itll hide the option label text but doesnt remove option all together.

varaible options

add_filter('woocommerce_variation_option_name', 'custom_hide_single_item_option', 10, 1);
function custom_hide_single_item_option($term_name)
{
    // Get the current user's roles
    $user = wp_get_current_user();
    $user_roles = (array)$user->roles;

    // Define the roles to exclude
    $roles_to_exclude = array('reseller', 'reseller 1', 'administrator');

    // If the user has any of the excluded roles, remove the "Single Item (1pc)" option
    if (array_intersect($user_roles, $roles_to_exclude) && $term_name === 'Single Item (1pc)') {
        return false;
    }

    return $term_name;
}

Ive provided php snippet im using and screenshot shows results of that snippet.

2

Answers


  1. I dont really understand / see the problem in the description and/or image. The only thing i see is a dropdown with a possibility to buy 4. Do you want to remove the dropdown? In that case I don’t think the PHP is the problem?

    Login or Signup to reply.
  2. add_filter('woocommerce_dropdown_variation_attribute_options_args', 'hide_attribute_values_for_specific_user_roles', 10, 1);
    function hide_attribute_values_for_specific_user_roles( $args ) {
        $user = wp_get_current_user();
        $user_roles = (array) $user->roles;
    
        $roles_to_exclude = array('reseller', 'reseller 1', 'administrator');
    
        if ( count( array_intersect( $user_roles, $roles_to_exclude ) ) > 0 ) {
            // Your attribute can have a different slug
            $attribute_slug_to_hide = 'pa_quantity';
            
            // This is a term (attribute option) slug, not its name! You may need to replace this value with the one you have on your website
            $attribute_value_to_hide = 'single-item-1pc'; 
            
            if ( isset( $args['attribute'] ) && $args['attribute'] === $attribute_name_to_hide ) {
                $value_index = array_search( $attribute_value_to_hide, $args['options'] );
                
                if ($value_index !== false) {
                    unset($args['options'][$value_index]);
                }
            }
        }
    
        return $args;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search