Hiển thị những bài viết liên quan

08/06/2019 Việt Hải Thủ Thuật Wordpress 2017 view

Xin chào trong bài viết này mình sẽ chia sẻ cách đưa những bài viết liên quan theo thẻ Tag hoặc theo Category. Để hiển thị được các bài viết liên quan trong WordPress. Mình cần xác định rằng các bài post liên quan này chỉ hiển thị ở trang chi tiết bài post chứ không hiển thị ở bên ngoài các trang khác và ở trong code thì đó là file single.php.
Các bạn vào Appearance – Theme Editor – và tìm Single.php nhé :

1.Hiển thị bài viết theo Categories :

<!-- Hiển thị bài viết theo Categories -->
<?php
$categories = get_the_category($post->ID);
if ($categories) { $category_ids = array();
foreach($categories as $individual_category)
$category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts'=>5, // Số bài viết bạn muốn hiển thị.
'caller_get_posts'=>1 );
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<h3>Bài viết liên quan</h3>
<ul class="list-news-cta">';
while ($my_query->have_posts()) { $my_query->the_post(); ?>
<li>
<div class="news-img">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(array(85, 75)); ?></a>
</div>
<div class="item-list">
<h4><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>	</div>
</li>
<?php } echo '</ul>'; } }
?>

2.Hiển thị bài viết theo Tags :

<!-- Hiển thị bài viết theo Tag -->
<div id="related-post-tags">
<?php $tags = wp_get_post_tags($post->ID);
if ($tags) { $tag_ids = array();
foreach($tags as $individual_tag)
$tag_ids[] = $individual_tag->term_id;
// lấy danh sách các tag liên quan
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID), // Loại trừ bài viết hiện tại
'showposts'=>5, // Số bài viết bạn muốn hiển thị.
'caller_get_posts'=>1 );
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<h3>Bài viết liên quan</h3><ul>';
while ($my_query->have_posts()) {
$my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php } echo '</ul>'; } } ?>
</div>