WordPress.org

Ready to get started?Download WordPress

Forums

How to display the parent category in the archive? (4 posts)

  1. biellebrunner
    Member
    Posted 1 year ago #

    I wanted to display the parent category name before the actual category in my archives page. It currently is:

    <h1>Categoria: <b>"<?php echo single_cat_title(); ?>"</b></h1>

    I googled and landed on this topic, suggesting that I replace <?php echo single_cat_title(); ?> for <?php if( $category->parent ) { echo get_the_category_by_ID($category->parent) . ' - '; } single_cat_title(); ?>, but it didn't work. It still shows only the child category name.

    I also tried <?php echo get_the_category_by_ID($category->parent); ?> - <?php single_cat_title(); ?>, but got an error saying "CATCHABLE FATAL ERROR: OBJECT OF CLASS WP_ERROR COULD NOT BE CONVERTED TO STRING IN /HOME/.../ARCHIVE.PHP ON LINE 8"

    How can I get something like:
    <h1>Categoria: <b>"<parent category> - <?php echo single_cat_title(); ?>"</b></h1>

    Thanks.

  2. Hristo SiteGround
    Member
    Posted 1 year ago #

    Hello,

    You can use the get_category_parents function to do that:

    <?php echo get_category_parents($cat, TRUE, ' &raquo; '); ?>

  3. biellebrunner
    Member
    Posted 1 year ago #

    Thank you. It works perfectly.
    Just one more question: is there any way to not get a » after the last category is displayed? So it'd be "Parent Category » Child Category" instead of "Parent Category » Child Category » "?
    Thanks.

  4. biellebrunner
    Member
    Posted 1 year ago #

    Ok. Another thing.
    I'd like to have the categories displayed before the title of a post when in a single page.
    Like "Parent Category » Child Category » Post Title". When I tried just using the get_category_parents function like:

    <span class="title">
    	<?php echo get_category_parents($cat, TRUE, ' » '); ?> <a
    href="<?php echo get_permalink() ?>" rel="bookmark" <?php the_title();
    ?>><?php the_title(); ?></a>
    </span>

    it didn't work and I got the error "catchable fatal error: object of class wp_error could not be converted to string in /home/.../single.php on line 7".

    Is there anyway to do that?

Topic Closed

This topic has been closed to new replies.

About this Topic