How to display the category of a post in WordPress using the_category
The the_category
function in WordPress is used to display the categories of a post. It can be useful in organizing and presenting content to readers, allowing them to easily navigate through related topics. By using this function, website owners can provide a clear and structured way for users to explore content based on specific categories.
Parameters Accepted by the the_category Function
The the_category
function accepts the following parameters:
$separator
(string, optional. Default value: ”): Separator between the categories. By default, the links are placed in an unordered list. An empty string will result in the default behavior.$parents
(string, optional. Default value: ”): How to display the parents. Accepts ‘multiple’, ‘single’, or empty.$post_id
(int, optional. Default value: false): ID of the post to retrieve categories for. Defaults to the current post.
Value Returned by the the_category Function
The the_category
function does not return a value.
Examples
How to display the categories of a post
<?php
the_category(', ');
?>
This code snippet uses the the_category
function to display the categories of a post, separated by commas.
How to display the categories of a post with a custom separator
<?php
the_category(' | ');
?>
This code snippet uses the the_category
function to display the categories of a post, separated by a custom separator (in this case, a pipe symbol).
How to display the categories of a post as a list
<?php
$categories = get_the_category();
foreach ($categories as $category) {
echo '<li>' . $category->name . '</li>';
}
?>
This code snippet first retrieves the categories of a post using the get_the_category
function, then loops through each category and displays them as a list using an HTML <li>
tag.
Conclusion
In conclusion, the the_category
function is a powerful tool for displaying the category or categories of a post within WordPress. By using this function, developers can easily customize the display of categories and improve the user experience on their websites. With its simple syntax and flexibility, the_category
function is a valuable addition to any WordPress developer’s toolkit.
Related WordPress Functions
- How to display post terms in WordPress using the_terms
- Using single_cat_title to get the current category title in WordPress
- Checking if a WordPress post belongs to a category using in_category
- How to a post's category list in WordPress using get_the_category_list
- How to display a list of WordPress categories with wp_list_categories
- How to retrieve the post category in WordPress using get_the_category