Skip to content

Instantly share code, notes, and snippets.

@sakilimran
Created April 9, 2017 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakilimran/f1f5032a200d5a896ae40579c2938e24 to your computer and use it in GitHub Desktop.
Save sakilimran/f1f5032a200d5a896ae40579c2938e24 to your computer and use it in GitHub Desktop.
WooCommerce - Create shortcode to display product categories dropdown list
<?php
/**
* WooCommerce Custom Shortcode
* --------------------------
*
* Register a shortcode that creates a product categories dropdown list
*
* Use: [product_categories_dropdown]
*
*/
add_shortcode( 'product_categories_dropdown', 'woo_product_categories_dropdown' );
function woo_product_categories_dropdown() {
ob_start();
$args = array(
'order' => 'ASC',
'hide_empty' => 1,
'posts_per_page' =>'-1',
'parent' => 0,
);
$product_categories = get_terms( 'product_cat', $args );
echo "<select name='product_cat' class='dropdown_product_cat'><option value=''>Select Destination/Country</option>";
foreach( $product_categories as $category ){
echo "<option value = '" . esc_attr( $category->slug ) . "'>" . esc_html( $category->name ) . "</option>";
}
echo "</select>";
?>
<script type='text/javascript'>
/* <![CDATA[ */
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="product_cat"]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
if ( event.target.value !=='' ) {
location.href = "<?php echo home_url(); ?>/?product_cat="+event.target.value;
}
}
/* ]]> */
</script>
<?php
return ob_get_clean();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment