Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce - Create a product categories dropdown list in a shortcode
<?php
/**
* WooCommerce Extra Feature
* --------------------------
*
* Register a shortcode that creates a product categories dropdown list
*
* Use: [product_categories_dropdown orderby="title" count="0" hierarchical="0"]
*/
add_shortcode( 'product_categories_dropdown', 'woo_product_categories_dropdown' );
function woo_product_categories_dropdown( $atts ) {
extract( shortcode_atts(array(
'count' => '0',
'hierarchical' => '0',
'orderby' => ''
), $atts ) );
ob_start();
// Stuck with this until a fix for http://core.trac.wordpress.org/ticket/13258
wc_product_dropdown_categories( array(
'orderby' => ! empty( $orderby ) ? $orderby : 'order',
'hierarchical' => $hierarchical,
'show_uncategorized' => 0,
'show_counts' => $count
) );
?>
<script type='text/javascript'>
/* <![CDATA[ */
jQuery(function(){
var product_cat_dropdown = jQuery(".dropdown_product_cat");
function onProductCatChange() {
if ( product_cat_dropdown.val() !=='' ) {
location.href = "<?php echo esc_url( home_url() ); ?>/?product_cat=" +product_cat_dropdown.val();
}
}
product_cat_dropdown.change( onProductCatChange );
});
/* ]]> */
</script>
<?php
return ob_get_clean();
}
@frauschneize
Copy link

frauschneize commented Aug 16, 2015

Hey Mike, thanks for your work on this. One question though ... is there a way to preselect an entry from the list?

@Drugoy
Copy link

Drugoy commented Sep 20, 2016

@mikejolley, line #22 links to a ticket that was closed more than a year ago. That ticket also affects https://github.com/woothemes/woocommerce/blob/master/includes/widgets/class-wc-widget-product-categories.php#L208
Could you take a look at that?

@gfloresolea
Copy link

gfloresolea commented Mar 18, 2017

How can I add an "All products" link to the list? It works but if I want to go back to shop main page there's no link.

@chranger
Copy link

chranger commented Jan 30, 2018

My alternative for SEO friendly URLs:

				<script type="text/javascript">
				    <!--
				    var dropdown = document.getElementById("cat");
				    function onCatChange() {
				        if ( dropdown.options[dropdown.selectedIndex].value !=-1 ) {
				            location.href = "<?php echo esc_url( home_url( '/' ) ); ?>produkt-kategorie/"+dropdown.options[dropdown.selectedIndex].value;
				        }
				    }
				    dropdown.onchange = onCatChange;
				    -->
				</script>

@DavidsonVeniali
Copy link

DavidsonVeniali commented Feb 5, 2021

Hi! How to remove the counter next to the category?

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