ergoProxy
ergoProxy

Reputation: 93

Display category parents and their children

I would like to display all the categories related to a post, along with their parents.

Currently I have something like this: Dog, Female, London, Newborn

I'm using this code:

$categories_list = get_the_category_list( __( '</br> ', 'twentytwentyone' ) );
            if ( $categories_list ) {
                printf(
                    '<p class="cat-links"> ' . ( $categories_list ) . ' </p></div>'
                );
            }

But I would like to also display the parent category as such:

<----------->

Type: Dog

Gender: Female

Location: London

Age: Newborn

<----------->

Note: I have tried simply writing HTML to group these as such

  • Type
  • Gender
  • Location
  • Age
  • This doesn't work because the categories listed are not ordered, therefore sometimes the output will be something like (Gender: Dog, Location: Female ,Type: London)

    Thank you in advance!

    Upvotes: 0

    Views: 64

    Answers (1)

    ergoProxy
    ergoProxy

    Reputation: 93

    foreach(get_the_category() as $category){
                    echo ($category->parent?get_category($category->parent)->name.': ':'').$category->name.'</br>';
                }
    

    This worked!

    Upvotes: 1

    Related Questions