Created
April 9, 2017 09:26
-
-
Save sakilimran/f1f5032a200d5a896ae40579c2938e24 to your computer and use it in GitHub Desktop.
WooCommerce - Create shortcode to display product categories dropdown list
This file contains 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 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