-
-
Save erikyo/4f75fa6734d79fae73c251b60630a201 to your computer and use it in GitHub Desktop.
WooCommerce: activate product tabs from URL (support with history states, share link to tab with hash)
This file contains 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
<?php | |
/** | |
* wc_direct_link_to_product_tabs | |
* | |
* Allows you to create custom URLs to activate product tabs by default, directly from the URL. | |
* ex: http://mysite.com/my-product-name#reviews | |
* this fork add history.pushState and each tab will be treated as a page | |
* so you can use browser history back / forward to move along tabs | |
*/ | |
add_action( 'wp_footer', function () { | |
if ( is_product() ) { | |
?> | |
<script> | |
jQuery(document).ready(function ($) { | |
// when the tab is clicked update the url | |
$(".tabs a").click(function () { | |
const nextTab = $(this).parent('li').attr("id").replace('tab-title-', ''); | |
window.history.pushState(null, null, "#" + nextTab); | |
}); | |
// on load and on hashchange (usually on history back/forward) | |
$(window).on('load hashchange', function () { | |
if( typeof window.location.hash !== undefined ) { | |
// get the tab name (or the first tab name) | |
const tab = window.location.hash.replace('#', '') || $('.wc-tabs li:first').attr("id").replace('tab-title-', ''); | |
// the tabs label | |
$('.wc-tabs .active').removeClass('active'); | |
$('li.' + tab + '_tab').addClass('active'); | |
// the tabs content | |
$('.woocommerce-Tabs-panel').hide(); | |
$('#tab-' + tab).show(); | |
} | |
}) | |
}); | |
</script> | |
<?php | |
} | |
}, 99 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment