How to retrieve the post category in WordPress using get_the_category

The get_the_category function in WordPress retrieves the categories of a post. It can be useful for displaying the categories that a post belongs to, allowing for better organization and navigation within a website.

Using get_the_category can help in creating a more user-friendly experience for visitors by providing them with easy access to related content within the same category.

Parameters accepted by get_the_category function

  • $post_id (int, optional): The post ID. Defaults to current post ID if not specified.

Value returned by get_the_category function

The function returns an array of WP_Term objects, one for each category assigned to the post.

Examples

How to get the category of a post in WordPress

$category = get_the_category( $post_id );
if ( ! empty( $category ) ) {
 echo esc_html( $category[0]->name );
}

This code snippet retrieves the category of a specific post using the get_the_category function and then displays the category name using esc_html to sanitize the output.

How to display all categories of a post in WordPress

$categories = get_the_category();
foreach ( $categories as $category ) {
 echo esc_html( $category->name ) . ', ';
}

This code snippet retrieves all the categories of a post using the get_the_category function and then loops through each category to display their names using esc_html to sanitize the output.

How to check if a post belongs to a specific category in WordPress

$categories = get_the_category();
foreach ( $categories as $category ) {
 if ( $category->name === 'News' ) {
 echo 'This post belongs to the News category';
 }
}

This code snippet retrieves all the categories of a post using the get_the_category function and then checks if the post belongs to a specific category using a foreach loop and an if statement.

Conclusion

In conclusion, the get_the_category function is a useful tool for retrieving the categories of a post in WordPress. It provides a simple and efficient way to access and display the categories associated with a particular post, making it easier for developers to create dynamic and customized content. By understanding how to use this function effectively, developers can enhance the user experience and improve the functionality of their WordPress websites.

Related WordPress Functions