子类别在父页面上设置为 current-cat
Child category is set current-cat on parent page
我的父类别有子类别。我在父类别页面上列出子类别。
我正在使用 archive.php 模板。
现在我在父类别页面上遇到 current-cat
class 问题。
似乎我的第一个子类别在父类别页面上得到 current-cat
class。此 current-cat
class 应仅在当前类别页面上打开。
例如,我的父类别是 Fruits。当我在 Fruits (category/fruits) 页面上时,我可以看到子类别 Apple、Orange、香蕉。问题是 Apple 在 Fruits 页面上得到 current-cat
class。
只有在 Apple 页面 (category/fruits/apple) 上才应该得到 class。
这是我当前的代码:
global $wp_query;
$ID = $wp_query->posts[0]->ID;
$postcat = get_the_category($ID);
$cat = $postcat[0]->cat_ID;
$thiscat = get_category ($cat);
$parent = $thiscat->category_parent;
if ($parent == 0) {
}
else {
$subcategories = get_categories('child_of='.$parent);
$items='';
foreach($subcategories as $subcat) {
if($thiscat->term_id == $subcat->term_id)
$current = ' current-cat';
else $current = '';
$items .= '
<li class="cat-item cat-item-'.$subcat->term_id.$current.'">
<a href="'.get_category_link( $subcat->term_id ).'" title="'.$subcat->description.'">'.$subcat->name.' </a>
</li>';
}
echo "<ul>$items</ul>";
}
?>
如何修复我的代码?
当您在 archive 模板上时,此代码:
global $wp_query;
$ID = $wp_query->posts[0]->ID;
$postcat = get_the_category($ID);
$cat = $postcat[0]->cat_ID;
$thiscat = get_category ($cat);
正在从第一个 post 加载类别 。第一个 post 可能属于一个、两个或多个类别,因此以这种方式获取类别 ID 并不可靠。
相反,还有一些其他方法 - 试试这个方法 - 来获取要加载存档的类别 ID:
$cat = get_query_var('cat');
$thiscat = get_category($cat);
$parent = ($thiscat->category_parent) ? $thiscat->category_parent : $thiscat->term_id;
我的父类别有子类别。我在父类别页面上列出子类别。
我正在使用 archive.php 模板。
现在我在父类别页面上遇到 current-cat
class 问题。
似乎我的第一个子类别在父类别页面上得到 current-cat
class。此 current-cat
class 应仅在当前类别页面上打开。
例如,我的父类别是 Fruits。当我在 Fruits (category/fruits) 页面上时,我可以看到子类别 Apple、Orange、香蕉。问题是 Apple 在 Fruits 页面上得到 current-cat
class。
只有在 Apple 页面 (category/fruits/apple) 上才应该得到 class。
这是我当前的代码:
global $wp_query;
$ID = $wp_query->posts[0]->ID;
$postcat = get_the_category($ID);
$cat = $postcat[0]->cat_ID;
$thiscat = get_category ($cat);
$parent = $thiscat->category_parent;
if ($parent == 0) {
}
else {
$subcategories = get_categories('child_of='.$parent);
$items='';
foreach($subcategories as $subcat) {
if($thiscat->term_id == $subcat->term_id)
$current = ' current-cat';
else $current = '';
$items .= '
<li class="cat-item cat-item-'.$subcat->term_id.$current.'">
<a href="'.get_category_link( $subcat->term_id ).'" title="'.$subcat->description.'">'.$subcat->name.' </a>
</li>';
}
echo "<ul>$items</ul>";
}
?>
如何修复我的代码?
当您在 archive 模板上时,此代码:
global $wp_query;
$ID = $wp_query->posts[0]->ID;
$postcat = get_the_category($ID);
$cat = $postcat[0]->cat_ID;
$thiscat = get_category ($cat);
正在从第一个 post 加载类别 。第一个 post 可能属于一个、两个或多个类别,因此以这种方式获取类别 ID 并不可靠。
相反,还有一些其他方法 - 试试这个方法 - 来获取要加载存档的类别 ID:
$cat = get_query_var('cat');
$thiscat = get_category($cat);
$parent = ($thiscat->category_parent) ? $thiscat->category_parent : $thiscat->term_id;