Access WooCommerce Product Tabs Directly via URL

Here is a quick snippet that I wanted to do for a long time. The aim is to allow you to create custom URLs to access products page with a specific tab active. By default, when you access a product page, the “description tab” is active by default, but with this snippet you can open the reviews tab (for example) directly from the URL. Useful isn’t it?

To use is it, simply add the tab name after a #, for example: http://mysite.com/my-product-name**#reviews**

Simple right?

To be able to use this method, simply paste the following code in the file called functions.php in your theme folder:

<?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
*/
function wc_direct_link_to_product_tabs() {
	if( is_product() ) {
	?>
	<script type="text/javascript">
		jQuery(document).ready(function($) {

		    if( window.location.hash ) {

			    // Vars
			    var tab 		= window.location.hash.replace('#', '');
			    var tab_content = 'tab-' + tab;

		    	// Tabs
		    	$( 'li.description_tab' ).removeClass( 'active' );
				$( 'li.' + tab + '_tab' ).addClass( 'active' );

				// Tabs content
				$( '#tab-description' ).hide();
				$( '#' + tab_content ).show();
			}

		    // when the tab is selected update the url with the hash
			$(".tabs a").click( function() {
				window.location.hash = $(this).parent('li').attr("class").replace(' active', '').replace('_tab', '');
			});

		});
		</script>
	<?php
	}
}

add_action( 'wp_footer', 'wc_direct_link_to_product_tabs', 30 );

And guess what? It works no matter the permalinks structure is ;-)

Here is the result:

woocommerce-enable-tab