Using WordPress ‘category_description()’ PHP function

The category_description() WordPress PHP function retrieves the description of a given category.

Usage

To use the category_description() function, you can simply call it with an optional category ID. If no ID is provided, it will default to the current category ID.

echo category_description(5);

In this example, it will output the description of the category with the ID 5.

Parameters

  • $category (int) – Optional. The ID of the category. Defaults to the current category ID if not provided.

More information

See WordPress Developer Resources: category_description()
This function has been a part of WordPress core since version 1.0.0. There is no deprecation information available as of the last update. Related functions include single_cat_title(), get_category_by_slug(), and get_the_category().

Examples

Displaying Category Description by ID

<div>
    echo category_description(3);
</div>

This code will display the description of the category with ID 3.

Using a Category Slug to Display Description

echo category_description(get_category_by_slug('my-category')->term_id);

This code retrieves the category ID using the slug ‘my-category’ and then fetches the description for this category.

Displaying Category Title with Description

<div>
    <strong>
        single_cat_title(__('Currently browsing', 'textdomain'));
    </strong>: 
    echo category_description();
</div>

In this example, the category title and description are displayed together. The category title is prefixed with ‘Currently browsing’. If the current category title is ‘WordPress’, and assuming its description is ‘A wonderful CMS’, the output will be ‘Currently browsing WordPress: A wonderful CMS’.

Check before Display

if (category_description()) {
    echo '<div>' . category_description() . '</div>';
}

In this case, the function checks if a category description exists before trying to display it. If it exists, it wraps the description in a div.

Using within a Loop

if (have_posts()) : 
    while (have_posts()) : the_post();
        echo '<div>' . category_description(get_the_category()[0]->cat_ID) . '</div>';
    endwhile; 
endif;

Here, we are looping through posts and displaying the description of the first category of each post. This can be useful if you want to display category descriptions alongside post content.