Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zealoushacker/b70b620c5acd98593690 to your computer and use it in GitHub Desktop.
Save zealoushacker/b70b620c5acd98593690 to your computer and use it in GitHub Desktop.
This script converts wordpress' default variable product's select to a bunch of swatch options. Style as you need it.
// this is super hacky, but it gets the job done
// this may be placed at the end of your theme's woocommerce/single-product/add-to-cart/variable.php
// or in the appropriate js file that you load via wp_enqueue_scripts
// if you want to be clean about it
(function($) {
var $variationsForm = $('form.variations_form');
$variationsForm.find('select').each(
function(i, select){
var $select = $(select);
$select.find('option').each(function(j, option){
var $option = $(option);
if (!$option.val()) {
return;
}
var variationObj = $.grep($variationsForm.data('product_variations'),
function(variation) {
return variation.attributes.attribute_pa_finish === $option.val();
}
)[0];
// Create a radio:
var $radio = $('<input type="radio" />');
// Set name and value:
$radio.attr('name', $select.attr('name')).attr('value', $option.val());
// Set checked if the option was selected
if ($option.attr('selected')) $radio.attr('checked', 'checked');
// Set the radio's attribute_name
$radio.attr('data-attribute_name', $select.attr('data-attribute_name'));
// Set the radio's attribute_id
$radio.attr('data-attribute_id',
variationObj.variation_id
);
// Make sure to set the variation id on the hidden field if the option was selected
// Lame wordpress for the win
if ($option.attr('selected')) {
$variationsForm.find(' input[name="variation_id"]' ) .val( $radio.attr('data-attribute_id') );
}
// Insert radio before select box:
$select.before($radio);
// Create the image swatch
var $swatch = $('<img />');
// Set the image swatch's source
$swatch.attr('src', variationObj.image_src);
// Grab the price html from the variationObj
var priceHtml = variationObj.price_html;
// Insert a label:
$select.before(
$("<label />").attr('for', $select.attr('name')).html(
// combine the swatch html and the priceHtml
$swatch.html() + priceHtml
)
);
// Insert a <br />:
$select.before("<br/>");
});
$select.remove();
}
);
// on select of a radio button
$('form.variations_form input:radio').change(
function() {
if (this.checked) {
// set the variation id on the hidden field
// again, lame wordpress =)
// but, we got it figured out, which is key
$variationsForm.find(' input[name="variation_id"]' ) .val( $(this).attr('data-attribute_id') );
}
}
);
// wordpress fucks with the add to cart button,
// thinking we forgot to add variations
// but, we'll tell it what's what
$('.single_variation_wrap').show();
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment