• On child category pages I need to get the parent of the current category. I tried:

    <?php if (is_category( )) {
    
    $thiscat = get_category( get_query_var( 'cat' ) );
    $catid = $thiscat->cat_ID;
    $parent = $catid->category_parent;
    
    if (!empty ($parent) ) {
    echo $parent;
    }
    else {
    echo '<span>this is a parent category</span>';
    }
    } ?>

    but I think category_parent only works with posts, not categories.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You’re trying to get category_parent from the wrong variable; you’ll want to get it from $thiscat instead:

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

    At this point, $parent contains the ID of the parent category (or 0 if the category has no parent), and then you can call get_the_category_by_ID() to get the category name.

    Thread Starter jrcollins

    (@jrcollins)

    Hey thanks! I was wondering what I was doing wrong.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to get the parent category of the current category?’ is closed to new replies.