2

I'm trying to display a list of categories in a PHP enabled text widget. On child category pages I need to get the id of the current category's parent category and then use that to return a list of all that category's child categories except the current category.

I tried the following code but it's not working:

<?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'
        ) );
} ?>

This displays both the parent categories and child categories.

2

I now realize there's an easier way to do this:

<?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'
        ) );
}
} ?>
0

This seems to be working:

<?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>';
        }
}
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.