Tạo bài viết liên quan cho WordPress

Bài viết liên quan là gì?

Bài viết liên quan là các bài viết cùng tag hoặc cùng chủ để trong website để điều hướng và trải nghiệm người dùng trong website của bạn. Điều này sẽ giúp website của bạn có thông tin rõ ràng hơn và trở lên uy tín trong mắt google khi SEO. Vậy tạo bài viết liên quan như thế nào? Trong bài này Học Khôn sẽ hướng dẫn cách thức tạo bài viết liên quan

Code bài viết liên quan WordPress

Để thực hiện code này các bạn phải nắm được một chút về WordPress. Theo đó, các bạn có thể lưu lại theme trước xử lý lý hoặc sử dụng Child Theme tránh làm hỏng Website

1. Code lấy bài viết liên quan theo chuyên mục

<?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), //Bỏ qua bài viết hiện tại
'posts_per_page' =>5, // Số bài viết bạn muốn hiển thị.
'caller_get_posts'=>1,
'no_found_rows'   =>true //Bỏ qua load phân trang tăng hiệu suât query
);
$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">';
while ($my_query->have_posts())
{
$my_query->the_post();
?>
<li>
<div class="new-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. Code lấy bài viết liên quan theo Tag

<!-- Hiển thị bài viết theo Tag -->
<div id="relatedposttags">    
<?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
'posts_per_page'=>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>

Các bạn có thể chèn code trên vào file single.php hoặc file tương ứng trong theme để lấy bài viết liên quan.