Skip to content

Instantly share code, notes, and snippets.

@shameemreza
Created September 3, 2025 05:21
Show Gist options
  • Select an option

  • Save shameemreza/6289ff03205de1c89db7b2e1ead74af7 to your computer and use it in GitHub Desktop.

Select an option

Save shameemreza/6289ff03205de1c89db7b2e1ead74af7 to your computer and use it in GitHub Desktop.
Automatically reset product variation selections after a successful Add to Cart (AJAX or non-AJAX).
/**
* Reset variation selections after successful add to cart
*/
add_action( 'wp_footer', function() {
if ( ! is_product() ) {
return;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
// Function to reset variations
function resetVariations() {
var $form = $('form.variations_form');
if ($form.length > 0) {
// Method 1: Click the Clear link if it exists
var $resetLink = $form.find('.reset_variations');
if ($resetLink.length > 0 && $resetLink.is(':visible')) {
$resetLink.trigger('click');
} else {
// Method 2: Manual reset
$form.find('.variations select').each(function() {
$(this).val('').trigger('change');
});
$form.trigger('reset_data');
}
}
}
// Listen for AJAX add to cart success
$(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) {
// Delay slightly to ensure the success message is shown first
setTimeout(function() {
resetVariations();
}, 100);
});
// Also handle form submission for non-AJAX add to cart
$('form.variations_form').on('submit', function(e) {
var $form = $(this);
// Set a flag to reset on page reload
if (!e.isDefaultPrevented()) {
sessionStorage.setItem('reset_variations', 'true');
}
});
// Check if we need to reset after page reload
if (sessionStorage.getItem('reset_variations') === 'true') {
sessionStorage.removeItem('reset_variations');
setTimeout(function() {
resetVariations();
}, 500);
}
});
</script>
<?php
});
@shameemreza
Copy link
Author

CleanShot 2025-09-03 at 11 43 35

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment