Skip to content

Instantly share code, notes, and snippets.

@corsonr
Last active March 2, 2021 18:14
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save corsonr/6681929 to your computer and use it in GitHub Desktop.
Save corsonr/6681929 to your computer and use it in GitHub Desktop.
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();
$c = $count;
$h = $hierarchical;
$o = ( isset( $orderby ) && $orderby != '' ) ? $orderby : 'order';
// Stuck with this until a fix for http://core.trac.wordpress.org/ticket/13258
woocommerce_product_dropdown_categories( $c, $h, 0, $o );
?>
<script type='text/javascript'>
/* <![CDATA[ */
var product_cat_dropdown = document.getElementById("dropdown_product_cat");
function onProductCatChange() {
if ( product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value !=='' ) {
location.href = "<?php echo home_url(); ?>/?product_cat="+product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value;
}
}
product_cat_dropdown.onchange = onProductCatChange;
/* ]]> */
</script>
<?php
return ob_get_clean();
}
@TChord22
Copy link

TChord22 commented Jun 3, 2019

Remove the <?php at the top of this piece of code when you paste it into your functions.php page.
Happy Coding!

@jkpvs14
Copy link

jkpvs14 commented Mar 12, 2020

Hi, I added this code to my child theme and also added some extra CSS to only show this on my mobile views - works great for that.

Just two questions, what do I need to change in the code to rather the categories order not go by title but sort it by the category order I've set on the admin side?

And secondly, how do I remove the number of items showing in the brackets after each category name e.g. Category (3) ?

Thank you in advance.

Regards,
Jhorene

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