How to use get_the_category() in WordPress

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:

  1. First, make sure you’re using this function within the loop. It will not work outside of the loop.
  2. Call the function get_the_category() and assign the result to a variable. For example, $categories = get_the_category();
  3. You can then loop through the categories using a foreach loop. For example:
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.

  1. 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:

$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.