Last active
March 2, 2021 18:14
-
-
Save corsonr/6681929 to your computer and use it in GitHub Desktop.
WooCommerce - Create a product categories dropdown list in a shortcode
This file contains hidden or 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 | |
/** | |
* 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(); | |
} |
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
Remove the <?php at the top of this piece of code when you paste it into your functions.php page.
Happy Coding!