fbpx
Want To Add Extra Images Per Product Variation? Download This Free Plugin

Add a class or data attribute to each swatch (variation)

I’m looking to add a unique class or data attribute to each variation swatch using a filter or other method. For context, this class or data attribute needs to contain meta data that is specific to the variation. It looks like the “woo_variation_swatches_html” filter may be the way to go about it, but I was hoping that you would be able to provide some recommendations for how to accomplish this. For an example of what I’m trying to do, I’d like to update the swatch HMTL output from this:

<li aria-checked="false" tabindex="0" data-attribute_name="attribute_color" class="variable-item image-variable-item image-variable-item-shocking-pink" title="Shocking Pink" data-title="Shocking Pink" data-value="Shocking Pink" role="radio" data-wvstooltip-out-of-stock=""></li>

To something like this:

<li aria-checked="false" tabindex="0" data-attribute_name="attribute_color" class="variable-item image-variable-item image-variable-item-shocking-pink CUSTOM-CLASS-HERE" title="Shocking Pink" data-title="Shocking Pink" data-value="Shocking Pink" role="radio" data-wvstooltip-out-of-stock=""></li>

Or, with a custom data attribute:

<li aria-checked="false" tabindex="0" data-custom_data="CUSTOM VALUE HERE" data-attribute_name="attribute_color" class="variable-item image-variable-item image-variable-item-shocking-pink" title="Shocking Pink" data-title="Shocking Pink" data-value="Shocking Pink" role="radio" data-wvstooltip-out-of-stock=""></li>

 

Any guidance or example code would be welcome, and thank you!

Hakik Zaman

Hi Courtney,

Thanks for reaching out to us.

Please try the following snippet using a plugin called Code Snippets. You can also add the following snippet using the child theme’s functions.php file:

add_filter( 'woo_variation_swatches_variable_item_custom_attributes', function( $html_attributes, $data, $attribute_type, $variation_data ){
$html_attributes[ 'data-custom_data' ] = esc_attr( "CUSTOM VALUE HERE" );
return $html_attributes;
}, 10, 4 );

Note: It is recommended to add the Custom Code to the child theme’s functions.php file, to avoid any data loss while updating the Parent Theme.

Then you will get the markup like this screenshot- https://paste.pics/5d989ebd47bb8e18f9f1f87368d4974a

Hope to hear from you soon.

Thank You