I managed to get this workign as I exactly wanted. And that was
- Call for page reload when variation is selected
- Pass Variation ID value into URL as attribute which I can process after reload on a single page using $_GET
- Keep the selected option
I am calling the script under:
add_action( 'woocommerce_before_add_to_cart_quantity', 'xenon_variation_modification' );
function xenon_variation_modification() {
global $product;
if ( $product->is_type('variable') ) {
global $post;
?>
<script>
jQuery(function($){
setTimeout( function(){
$( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) {
//alert( variation.variation_id );
console.log( variation.variation_id );
var url = '<?php echo get_permalink($post->ID);?>';
//$('input.variation_id').change( function(){
console.log('You just selected variation #' + variation.variation_id);
var attributes = [];
var allAttributesSet = true;
$('table.variations select').each(function() {
var value = $(this).val();
if (value) {
attributes.push({
id: $(this).attr('name'),
value: value
});
} else {
allAttributesSet = false;
}
});
if (allAttributesSet) {
$.each(attributes,function(key, val) {
var attributeSlug = val.id.replace('attribute_pa_','');
url = url +'?variation_id='+ variation.variation_id +'&'+attributeSlug+'=' + val.value;
});
console.log('Relocating #' + variation.variation_id);
//window.location.replace(url);
window.location.href = url;
}
} );
}, 400 );
});
</script>
<?php
}
}
I have researched for this at following sources:
Get currently selected variation id from Woocommerce variable product
https://sarathlal.com/get-variation-product-data-on-selecting-variation-options-woocommerce/
https://wordpress.stackexchange.com/questions/280125/custom-url-for-each-product-variation-rewrite-rules