How to print child category and parent category in WordPress?

You are currently viewing How to print child category and parent category in WordPress?

How to print child category and parent category in WordPress?

Here is an example of how you can print the child categories and the parent category for a post in WordPress:

// Get the categories for the post
$categories = get_the_category();

// If there are categories
if ( ! empty( $categories ) ) {
    // Loop through the categories
    foreach( $categories as $category ) {
        // Print the category name
        echo esc_html( $category->name );

        // Check if the category has a parent
        if ( $category->parent ) {
            // If the category has a parent, get the parent category object
            $parent_category = get_category( $category->parent );
            // Print the parent category name
            echo ' (Parent Category: ' . esc_html( $parent_category->name ) . ')';
        }
    }
}

This code will print the name of each category for the post, along with the name of the parent category if the category has a parent.

WordPress comes with two default taxonomies called categories and tags to organize your content. Many websites use tags for specific topics of each article and categories for broader website sections.

Note: This code assumes you are using it inside the loop in a WordPress template file. If you are using it outside the loop, you will need to pass the post ID as a parameter to the get_the_category() function.

if you need any help in wordpress development click here

Leave a Reply