Forum

SHORTCODE BÀI VIẾT LIÊN QUAN THEO CHUYÊN MỤC WORDPRESS

Started by Huy Mạnh · 0 Replies
Avatar

Huy Mạnh


1 year ago

Posted: 2 months ago
Có thể bạn biết shortcode là 1 mã ngắn nên bạn copy chúng và có thể sử dụng ở nhiều nơi rất tiện lợi. Trong bài viết này mình chia sẻ 1 đoạn code ngắn để lấy các bài viết liên quan, hay các bài viết cùng 1 chuyên mục để hiển thị.

shortcode bài viết liên quan

Shortcode bài viết liên quan trong WordPress
Để tạo shortcode bài viết liên quan theo chuyên mục WordPress bạn có thể thêm đoạn bên dưới vào file functions.php.

function ghtech_related_posts_shortcode() {
$args = array(
'post_type' => 'post',
'posts_per_page' => '10',
'post__not_in' => array(get_the_ID()),
'orderby' => 'rand'
);
$i=0;
$related_posts = new WP_Query($args);
if ($related_posts->have_posts()) :
$output = '<ul class="list-top related-posts">';
while ($related_posts->have_posts()) : $related_posts->the_post();
$i++;
$output .= '<li class="related-post"><span class="number">' . $i . '</span>';
$output .= '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
$output .= '</li>';
endwhile;
$output .= '</ul>';
wp_reset_postdata();
else :
$output = '';
endif;
return $output;
}
add_shortcode('ghtech_related_posts', 'ghtech_related_posts_shortcode');


Giải thích sơ qua đoạn code bên trên

post_type Loại bài viết
posts_per_page số bài viết cần hiển thị
post__not_in loại bài viết hiện tại ra khỏi danh sách bài viết liên quan
orderby hiển thị ngẫu nhiên, bạn có thể đặt date để lấy các bài cùng chuyên mục mới đăng
Sau khi thêm code trên vào file functions.php bạn có thể sử dụng shorcode [ghtech_related_posts] để hiện vào nơi cần hiển thị các bài viết liên quan.

Hoặc sử dụng code php dưới đây để cho vào template.

<?php echo do_shorcode('[ghtech_related_posts]'); ?>

Bạn nên css để làm đẹp bài viết liên quan nhé, có thể sử dụng code css dưới đây để style chẳng hạn.

.list-top li{position:relative;padding:10px 0;height:50px;list-style:none}
.list-top span{font-size:18px;color:#fff;background-color:#ccc;width:35px;height:35px;border-radius:100%;text-align:center;line-height:35px;position:absolute;top:50%;transform:translateY(-50%);}
.list-top li:nth-child(2) span{background-color:#d0b07a;}
.list-top li:nth-child(1) span{background-color:#f25630;}
.list-top li:nth-child(3) span{background-color:#decbac;}
.list-top a{font-size:inherit;margin-left:45px;display:block;line-height:23px;text-decoration:none}


bài viết liên quan cho wordpressTuỳ theo web của bạn mà có thể chỉnh code lại cho phù hợp nhé, ở code này mình code css cho phù hợp khi đặt ở sidebar, nếu bạn muốn đặt ở cuối bài viết thì css lại để nó hiển thị ngang sẽ đẹp và phù hợp hơn.

Ngoài code thì bạn cũng có thể lên kho plugin của WordPress và tìm kiếm từ khoá như: Related Post để tìm những plugin giúp hiện các bài viết liên quan theo cat hoặc tag được code sẵn.