Last active
August 22, 2024 14:53
-
-
Save Paulsky/0ab9daa2abf25ff863a1f055ac260a9a to your computer and use it in GitHub Desktop.
Automatically selects the only available 'Variation Button' for Product Variations Swatches for WooCommerce.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function enqueue_script() | |
{ | |
$version = '1.0.0'; | |
if (is_product()) { | |
wp_enqueue_script('single-variation-form', get_stylesheet_directory_uri() . '/js/single-variation-form.js', ['jquery', 'vi-wpvs-frontend-script'], $version, true); | |
} | |
} | |
add_action('wp_enqueue_scripts', 'enqueue_script'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
'use strict'; | |
function autoSelectSingleVariations() { | |
$('.variations_form .vi-wpvs-variation-wrap').each(function() { | |
const wrapper = $(this); | |
const availableItems = wrapper.find('.vi-wpvs-option-wrap:not(.vi-wpvs-option-wrap-disable):not(.vi-wpvs-hidden)'); | |
const selectedItems = availableItems.filter('.vi-wpvs-option-wrap-selected'); | |
if (availableItems.length === 1 && !availableItems.attr('data-prevent-auto-select')) { | |
availableItems.click(); | |
} else if (selectedItems.length > 0 && !selectedItems.attr('data-prevent-auto-select')) { | |
selectedItems.click(); | |
} | |
}); | |
} | |
$(document).ready(function() { | |
let clickedVariation = false; | |
$('.vi-wpvs-option-wrap-selected').attr('data-prevent-auto-select', 'true'); | |
$('.variations_form').on('woocommerce_variation_has_changed', function() { | |
setTimeout(function() { | |
if (clickedVariation) { | |
autoSelectSingleVariations(); | |
} | |
}, 500); | |
}); | |
$('.variations_form').on('click', '.reset_variations', function() { | |
clickedVariation = false; | |
$('.vi-wpvs-option-wrap').removeAttr('data-prevent-auto-select'); | |
}); | |
$('.vi-wpvs-option-wrap').on('click', function() { | |
const button = $(this); | |
if (button.attr('data-prevent-auto-select') && !button.hasClass('vi-wpvs-option-wrap-selected')) { | |
clickedVariation = false; | |
button.removeAttr('data-prevent-auto-select'); | |
} else { | |
clickedVariation = true; | |
button.attr('data-prevent-auto-select', 'true'); | |
button.closest('.vi-wpvs-variation-wrap').find('.vi-wpvs-option-wrap').not(this).removeAttr('data-prevent-auto-select'); | |
} | |
}); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment