Having converted the drop-down for attribute and terms into buttons, I am looking for some help on adding color as an option for the color term.
If the term name is Yellow, the background of that button becomes #ffff00
and the color of it white (#fff). If the name is Blue, the background becomes #0000ff
and the text white -- and so forth.
I just need help adding one and I'll do the rest myself.
Based on How to convert select options (product attributes) to clickable divs in variable product page in WooCommerce? answer code, this is my attempt:
add_action( 'wp_footer', 'convert_attribute_and_terms_into_buttons' );
function convert_attribute_and_terms_into_buttons() { ?>
<script type="text/javascript">
jQuery(function($){
var clone = $( ".single-product div.product table.variations select" ).clone( true,true );
$( ".single-product div.product table.variations select option" ).each( function() {
$( this ).attr( 'data-parent-id', $( this ).parent().attr( 'id' ) );
}
);
$( ".single-product div.product table.variations select option" ).unwrap().each( function() {
if ( $ ( this ).val() == '' ) {
$( this ).remove();
return true;
}
var option = $( '<div class="custom_option" data-parent-id="'+$( this ).data( 'parent-id' )+'" data-value="'+$( this ).val()+'">'+$( this ).text()+'</div>' );
$( this ).replaceWith( option );
}
);
$( clone ).insertBefore( '.single-product div.product table.variations .reset_variations' ).hide();
$( document ).on( 'click', '.custom_option', function() {
var parentID = $( this ).data( 'parent-id' );
$( '.custom_option[data-parent-id='+parentID+']' ).removeClass( 'on' );
$( this ).addClass( 'on' );
$( ".single-product div.product table.variations select#"+parentID ).val( $ ( this ).data( "value" ) ).trigger( "change" );
}
);
$( ".single-product div.product table.variations select" ).each( function() {
if ( $ ( this ).find( "option:selected" ).val() ) {
var id = $( this ).attr( 'id' );
$( '.custom_option[data-parent-id='+id+']' ).removeClass( 'on' );
var value = $ ( this ).find( "option:selected" ).val();
$( '.custom_option[data-parent-id='+id+'][data-value='+value+']' ).addClass( 'on' );
}
});
});
</script>
<style>
div.custom_option {
display: inline-block;
border: 1px solid #333;
margin-right: 5px;
padding: 0px 10px 0px 10px;
cursor: pointer;
}
div.custom_option.on {
background-color: gray;
color: white;
}
</style>
<?php
}