Cray
Cray

Reputation: 5483

WooCommerce: Add class to variation dropdown

I want to add the class .form-control to the variation dropdown in the WooCommerce product pages.

It seems that there is an option to do so. I found the function wc_dropdown_variation_attribute_options.

The function has an class attribute:

function wc_dropdown_variation_attribute_options( $args = array() ) { 
$args = wp_parse_args( apply_filters( 'woocommerce_dropdown_variation_attribute_options_args', $args ), array( 
    'options' => false,  
    'attribute' => false,  
    'product' => false,  
    'selected' => false,  
    'name' => '',  
    'id' => '',  
    'class' => '',  
    'show_option_none' => __( 'Choose an option', 'woocommerce' ),  
 ) ); 

Is there any solution to add the class to the dropdown? I only found the function but no code/snippet to change the class attribute.

Edit: I found a snippet that is customizing the dropdown but I don't know how to use it for only adding the class: https://stackoverflow.com/a/47189725/1788961

Upvotes: 1

Views: 4152

Answers (1)

disinfor
disinfor

Reputation: 11533

The answer is in the apply_filters( 'woocommerce_dropdown_variation_attribute_options_args', $args )

You basically need to use that filter to access the $args that are being passed. In your particular situation, this is how you would do it:

add_filter( 'woocommerce_dropdown_variation_attribute_options_args', static function( $args ) {
    $args['class'] = 'form-control';
    return $args;
}, 2 );

What this does, is hooks into the woocommerce_dropdown_variation_attribute_options_args filter and passes the original $args to a static function. Then you basically set the value of the class index of the $args array. Then you return the $args.

Upvotes: 3

Related Questions