Hướng dẫn cách lấy và hiển thị Primary Category bài đăng cho wordpress

Cách lấy và hiển thị Primary Category bài đăng cho wordpress: Với tính năng Primary Category của WordPress, đôi khi chúng ta chỉ muốn truy xuất một Primary Category đó chứ không phải danh sách tất cả danh mục. Trong bài đăng này, Blog sẽ chỉ cho bạn cách lấy danh mục chính của một bài đăng.

Hướng dẫn cách lấy và hiển thị Primary Category bài đăng cho wordpress

Hướng dẫn cách lấy và hiển thị Primary Category bài đăng cho wordpress

Với một bài đăng mà nội dung của nó được nằm trong nhiều category thì khi bạn muốn hiển thị nó nằm trong danh mục nào với người đọc thì nên chọn cho nó một Primary Category mặc định, để làm được nó hãy thêm đoạn code sau vào web của bạn.

Thêm code vào functions

function get_primary_category($category){
  $useCatLink = true;
  // If post has a category assigned.
  if ($category){
    $category_display = '';
    $category_link = '';
    if ( class_exists('WPSEO_Primary_Term') )
    {
      // Show the post's 'Primary' category, if this Yoast feature is available, & one is set
      $wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() );
      $wpseo_primary_term = $wpseo_primary_term->get_primary_term();
      $term = get_term( $wpseo_primary_term );
      if (is_wp_error($term)) {
        // Default to first category (not Yoast) if an error is returned
        $category_display = $category[0]->name;
        $category_link = get_category_link( $category[0]->term_id );
      } else {
        // Yoast Primary category
        $category_display = $term->name;
        $category_link = get_category_link( $term->term_id );
      }
    }
    else {
      // Default, display the first category in WP's list of assigned categories
      $category_display = $category[0]->name;
      $category_link = get_category_link( $category[0]->term_id );
    }
    // Display category
    if ( !empty($category_display) ){
      if ( $useCatLink == true && !empty($category_link) ){
      return '<span class="post-category"><a href="'.$category_link.'">'.htmlspecialchars($category_display).'</a></span>';
      } else {
      return '<span class="post-category">'.htmlspecialchars($category_display).'</span>';
      }
    }
  }
}

Thêm code sau vào chỗ muốn hiển thị Primary Category

$category = get_the_category();

echo '<div class="post-category">';
echo get_primary_category($category);
echo '</div>';

Kết luận

Trên đây là cách lấy và hiển thị Primary Category bài đăng cho wordpress mà bạn có thể tham khảo. Hy vọng với hướng dẫn mà Blog thủ thuật máy tính f4vnn đã chia sẻ sẽ có ích với bạn. Chúc bạn thành công.


Xem Thêm Bài Viết
Nhạc DJ Nhạc Hay TikTok Truyện Ma

Rate this post