[英]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/ 您可以看到它在这里运行: 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
. 问题是,它无法识别子类别的父类别,因此,它不会转到
/product-category/cameras-photos/lens/
而是转到了/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? 有没有办法在URL上获得父类别?
<?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. 您需要修改JS以检查所选选项是否具有父选项,然后也打印父选项。 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.
这应该适用于您的网站,请注意,如果您要添加另一个可能要考虑使用for循环的级别,它只会检查一个级别。
$(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;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.