如何显示当前类别的上级类别的下级类别?

时间:2016-09-05 作者:jrcollins

我试图在一个支持PHP的文本小部件中显示一个类别列表。在子类别页面上,我需要获取当前类别父类别的id,然后使用该id返回除当前类别之外的所有该类别子类别的列表。

我尝试了以下代码,但不起作用:

<?php if (is_category( )) {

$thiscat = get_category( get_query_var( \'cat\' ) );
$catid = $thiscat->cat_ID;
$parent = $catid->category_parent;

$catlist = get_categories(
        array(
        \'child_of\' => $parent,
        \'orderby\' => \'id\',
        \'order\' => \'DESC\',
        \'exclude\' => $catid,
        \'hide_empty\' => \'0\'
        ) );
} ?>
这将显示父类别和子类别。

2 个回复
SO网友:jrcollins

我现在意识到有一种更简单的方法:

<?php   if (is_category( )) {

        $thiscat = get_category( get_query_var( \'cat\' ) );
        $catid = $thiscat->cat_ID;
        $parent = $thiscat->category_parent;

        if (!empty ($parent) ) {
        //child category pages

        $catlist = get_categories(
        array(
        \'child_of\' => $parent,
        \'orderby\' => \'id\',
        \'order\' => \'DESC\',
        \'exclude\' => $catid,
        \'hide_empty\' => \'0\'
        ) );
}
} ?>

SO网友:jrcollins

这似乎奏效了:

<?php if (is_category( )) {

$thiscat = get_category( get_query_var( \'cat\' ) );
$catid = $thiscat->cat_ID;
//create array from get_category_parents
$parent_list = (explode (\',\',get_category_parents($catid,false,\',\')));
$parent_name = ($parent_list[0]);
$parent = get_cat_ID( $parent_name );

$catlist = get_categories(
        array(
        \'child_of\' => $parent,
        \'orderby\' => \'id\',
        \'order\' => \'DESC\',
        \'exclude\' => $catid,
        \'hide_empty\' => \'0\'
        ) );
        //check if current category is parent category
        if ( $catid == $parent ) {
        echo \'<span>this is a parent category page</span>\';
        }
        else {
        echo \'<span>this is a child category page</span>\';
        }
}
?>