Blog lập trình

Chia sẻ mọi kiến thức về lập trình

Hiển thị bài viết liên quan cho custom post type trong cùng custom taxonomy


Trong đoạn code ví dụ dưới đây chúng ta có:
  • Custom post type có tên là devvn_quotes
  • Custom taxonomy là category_quotes
Để hiển thị bài viết liên quan bạn hãy đặt đoạn code này vào chỗ bạn muốn hiển thị. Có thể là single.phphoặc single-devvn_quotes.php tùy vào mỗi theme nhé
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
 * Code hiển thị bài viết liên quan cho custom post type trong cùng 1 custom taxonomy
 */
$postType = 'devvn_quotes';
$taxonomyName = 'category_quotes';
$taxonomy = get_the_terms(get_the_ID(), $taxonomyName);
if ($taxonomy){
   echo '<div class="relatedcat">';
   $category_ids = array();
   foreach($taxonomy as $individual_category) $category_ids[] = $individual_category->term_id;
   $args = array(
      'post_type' =>  $postType,
      'post__not_in' => array(get_the_ID()),
      'posts_per_page' => 3,
      'tax_query' => array(
         array(
            'taxonomy' => $taxonomyName,
            'field'    => 'term_id',
            'terms'    => $category_ids,
         ),
      )
   );
   $my_query = new wp_query($args);
   if( $my_query->have_posts() ):
      echo '<p>Bài viết liên quan:</p><ul>';
      while ($my_query->have_posts()):$my_query->the_post();
         echo '<li><a href="'.get_the_permalink().'" title="'.get_the_title().'">'.get_the_title().'</a></li>';
      endwhile;
      echo '</ul>';
   endif; wp_reset_query();
   echo '</div>';
}
Chú ý: hãy thay đoạn này thành custom post type và custom taxonomy của bạn
1
2
$postType = 'devvn_quotes';
$taxonomyName = 'category_quotes';
Share on Google Plus

About Blog chia sẻ kiến thức lập trình

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 nhận xét:

Đăng nhận xét