I have this code that shows all my categories in a dropdown menu.
You can see it running here: https://store.vtxfactory.org/products/
For the parent categories, it works like a charm. Problem is, it doesn't recognize the parent of the child categories, so instead of going to /product-category/cameras-photos/lens/
it goes to /product-category/lens
. It works too, but that's not what I'm trying to achieve.
Is there a way to get the parent categories on the url too?
<?php
function replace_id_for_slug($option){
$categories = get_categories("hide_empty=0");
preg_match('/value="(\d*)"/', $option[0], $matches);
$id = $matches[1];
$slug = "";
foreach($categories as $category){
if($category->cat_ID == $id){
$slug = $category->slug;
}
}
return preg_replace("/value=\"(\d*)\"/", "value=\"$slug\"", $option[0]);
}
$select = wp_dropdown_categories("hierarchical=true&hide_empty=0&echo=0&taxonomy=product_cat&value_field=slug&show_option_none=- Search by category...&show_count=1&selected=1&orderby=name");
$select = preg_replace_callback("#<option[^>]*>[^<]*</option>#", "replace_id_for_slug", $select);
echo $select;
?>
<script type="text/javascript"><!--
var dropdown = document.getElementById("cat");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value != -1 ) {
location.href = "<?php echo get_option('home');?>/product-category/"+dropdown.options[dropdown.selectedIndex].value+"/";
}
}
dropdown.onchange = onCatChange;
--></script>
Thanks.