Skip to content

Instantly share code, notes, and snippets.

@devidw
Last active May 7, 2023 07:57
Show Gist options
  • Save devidw/2f674f273fb556cb48c82dc1b70aff25 to your computer and use it in GitHub Desktop.
Save devidw/2f674f273fb556cb48c82dc1b70aff25 to your computer and use it in GitHub Desktop.
WooCommerce direct variation URL for variable products
/**
* Little JS snippet to automatically update the WooCommerce single product page URL with the needed parameters for the active variations' selection.
*
* Each time the user changes the variation selection, the URL is updated with the new parameters, so on hard refresh the selected variation is displayed.
*
* Also, fast way to get the direct URL to the selected variation.
*
* Paste it into your browser console and run it. Or use it in your theme/plugins.
*
* @see https://stackoverflow.com/a/73138077/13765033
*/
const els = document.querySelectorAll('.variations select')
// add el.name and el.value as query parameters to the URL
function updateURL(el) {
const url = new URL(window.location.href)
url.searchParams.set(el.name, el.value)
window.history.pushState({}, '', url.href)
}
// update the URL when the user changes the select
els.forEach(el => el.addEventListener('change', () => updateURL(el)))
Paste the below into a new entry of your browser's bookmarks bar and click on it on the given WC single product page:
javascript:(function()%7B%2F**%0A%20*%20Little%20JS%20snippet%20to%20automatically%20update%20the%20WooCommerce%20single%20product%20page%20URL%20with%20the%20needed%20parameters%20for%20the%20active%20variations'%20selection.%0A%20*%20%0A%20*%20Each%20time%20the%20user%20changes%20the%20variation%20selection%2C%20the%20URL%20is%20updated%20with%20the%20new%20parameters%2C%20so%20on%20hard%20refresh%20the%20selected%20variation%20is%20displayed.%0A%20*%20%0A%20*%20Also%2C%20fast%20way%20to%20get%20the%20direct%20URL%20to%20the%20selected%20variation.%0A%20*%20%0A%20*%20Paste%20it%20into%20your%20browser%20console%20and%20run%20it.%20Or%20use%20it%20in%20your%20theme%2Fplugins.%0A%20*%2F%0A%0Aconst%20els%20%3D%20document.querySelectorAll('.variations%20select')%0A%0A%2F%2F%20add%20el.name%20and%20el.value%20as%20query%20parameters%20to%20the%20URL%0Afunction%20updateURL(el)%20%7B%0A%20%20%20%20const%20url%20%3D%20new%20URL(window.location.href)%0A%20%20%20%20url.searchParams.set(el.name%2C%20el.value)%0A%20%20%20%20window.history.pushState(%7B%7D%2C%20''%2C%20url.href)%0A%7D%0A%0A%2F%2F%20update%20the%20URL%20when%20the%20user%20changes%20the%20select%0Aels.forEach(el%20%3D%3E%20el.addEventListener('change'%2C%20()%20%3D%3E%20updateURL(el)))%7D)()%3B
@alikamal1
Copy link

if you want to keep the behavior of the browser back button to the previous page instead of the previous selection, you can use replaceState instead of pushState

window.history.replaceState({}, '', url.href)

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