简体   繁体   中英

Grab parent from child categories on dropdown menu

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.

You need to modify your JS to check if the selected option has parent option and then print the parent option as well. This should work for your site, note that it only check for one level up if you'll add another level you might want to consider to use for loop instead.

$(document).ready(function() {
    $("#cat").change(function () {
        var selected = $("#cat option:selected");
        var destination = "<?php echo get_option('home');?>/product-category/"; 
        if(selected.attr("class") == "level-1"){
           destination += selected.prevAll("option.level-0:first").val()+"/";
        }
        destination += selected.val()+"/";
        location.href = destination;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM