get_the_category() is a WordPress function that is used to retrieve the categories that a post belongs to.
Here’s how to use it:
- First, make sure you’re using this function within the loop. It will not work outside of the loop.
- Call the function
get_the_category()and assign the result to a variable. For example,$categories = get_the_category(); - You can then loop through the categories using a
foreachloop. For example:
php
foreach ($categories as $category) {
echo '<a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a>';
}
In this example, we’re using get_category_link() to get the URL for the category archive page, and we’re using $category->name to display the category name.
- If you only want to display the first category that the post belongs to, you can use
get_the_category()[0]instead of$categories.
Here’s an example:
bash
$category = get_the_category()[0];
echo '<a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a>';
That’s it! You now know how to use get_the_category() in WordPress.











