假设你有WordPress网站,例如具有以下结构:
Dog (Top Level Category)
-Boxer (Sub Level Category)
--Brindle (Third Level Category)
--Reverse Brindle (Third Level Category)
-Golden Retriever (Sub Level Category)
-Labrador (Sub Level Category)
Cat (Top Level Category)
-Siamese (Sub Level Category)
--Siamese Black (Third Level Category)
--Siamese White (Third Level Category)
-Bengal (Sub Level Category)
-Ragdoll (Sub Level Category)
尝试开发一个函数来添加到所有页面模板,例如category.php,single.php等,这样侧边菜单将根据您的位置显示完整的类别层次结构。例如,如果您正在查看狗类别,或拳击手,或者使用斑纹,它将显示与上面相同的完整Dog菜单,每个菜单都链接到各自的类别,而您所在的类别将会有一个活跃的类别。
此外,在页面顶部输出顶级类别和您所在的类别。例如,如果在反向斑纹线上会说“Dog> Reverse Brindle”或者如果在Dog上只会说“Dog”或者如果在Boxer上会说“Dog> Boxer。”
它有点工作但是有很多冗余代码并且在同一页面上没有按预期工作。
答案 0 :(得分:4)
以下是使用wp_list_categories()显示所有类别的整个结构化列表的方法。
<?php
//Get whatever object we're working with (category or post?)
$thisObj = get_queried_object();
//If it's a post, get the category ID
if(!is_null($thisObj->ID)){
$currentCat = get_the_category();
$currentCatID = $currentCat[0]->cat_ID;
}
//If it's a category, get the ID a different way
elseif(!is_null($thisObj->term_id)){
$currentCatID = $thisObj->term_id;
}
//Call wp_list_categories to echo the list of categories
$args = array(
'current_category' => $currentCatID, //This assigns the "current-cat" class to the correct item in the list so you can style it differently
'child_of' => 0,
'hide_empty' => 0,
'order' => 'ASC',
'orderby' => 'name',
);
wp_list_categories($args);
然后,您可以使用以下方式设置列表中活动类别的样式:
(还有更多的类可以用来设置列表的其余部分。只需看看它生成的HTML)
.current-cat{
/* whatever you want */
}
这应该在页面顶部进行:
<?php
$thisObj = get_queried_object(); // Find out what we're displaying (Category or post?)
if(!is_null($thisObj->ID)){ // If it's a post, get the category ID
$currentCat = get_the_category();
$currentCatID = $currentCat[0]->cat_ID;
}
elseif(!is_null($thisObj->term_id)){ // If it's a category, get the ID a different way
$currentCatID = $thisObj->term_id;
}
// Get the name of the Category we're starting with
$currentCatName = get_cat_name($currentCatID);
//Get the ID then the name of the highest parent Category
$topParentID = end(get_ancestors($currentCatID, 'category'));
$topParentName = get_cat_name($topParentID);
if(!$topParentName){ // If we're already at the highest category, just save the name
$finalAnswer = $currentCatName;
}
else{ // Otherwise, display "Top Parent > Current Cat"
$finalAnswer = $topParentName . ' > ' . $currentCatName;
}
echo $finalAnswer; //Ta-da!