Thông tin liên hệ

Quốc Trần - Quận Gò Vấp, TP. Hồ Chí Minh

Liên hệ hỗ trợ 0906891294 Zalo
Mạng xã hội
How to get the category title in a post in WordPress?
Avatar
Cá Mập
  • 09/01/2024
  • Blog

When you are viewing a detailed post and want to display the current category of the post, you need to add the following code snippet to your single page:

<?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?>

This code utilizes the get_the_category() function to retrieve the categories associated with the current post. The foreach loop then iterates through each category, and echo $category->cat_name is used to display the name of each category. The result is the presentation of the current post’s categories on your single page.

Alternatively, you can use categories and link to them:

<?php foreach((get_the_category()) as $category) { echo '<a href="'.get_term_link($category).'">'.$category->cat_name.'</a> '; } ?> 

This code enhances the previous snippet by wrapping the category names with <a> tags, creating clickable links to the respective category archives. The get_term_link($category) function generates the URL for each category, and the category name is displayed as a clickable link. This modification allows users to navigate directly to the category pages from the displayed post on your single page.

How to get category by post id wordpress

echo wp_get_post_terms(get_the_ID(), 'category')[0]->name;

You can replace “category” with a custom taxonomy of your choice.

Đánh giá bài viết
Avatar
Cá Mập

Cá Mập code lập trình wordpress, chia sẽ kiến thức, thủ thuật về web wordpress. Liên hệ làm việc 0906 891 294 ( Phone, Zalo )