Hiển thị bài viết cùng chuyên mục không dùng plugin

104

Nhằm giúp người đọc tiện tham khảo bài viết, chúng ta thường cho hiển thị các bài viết liên quan. HT cũng đã có bài hướng dẫn thực hiện lấy bài viết liên quan dựa theo từ khóa. Hôm nay, HT sẽ hướng dẫn các bạn lấy bài viết liên quan dựa theo chuyên mục, chúng ta tạm gọi là bài viết cùng chuyên mục.

Bạn copy và paste đoạn code sau và file functions.php (custom_functions.php nếu bạn sử dụng thesis)

function bai_viet_chuyen_muc( $atts ) {
extract(shortcode_atts(array(
‘limit’ => ’5′,
), $atts));
global $post;
$related_cat=’<ul>’;
$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’=>$limit,
‘caller_get_posts’=>1
);
$rl_cat = new wp_query($args);
if( $rl_cat->have_posts() ) {
while ($rl_cat->have_posts()) {
$rl_cat->the_post();
$post = get_post($post_id);
$title=$post->post_title;
$link=get_permalink($post->id);
$related_cat.=’<li><a href=”‘.$link.’” title=”Permanent Link to ‘.$title.’”>’.$title.’</a></li>’;
}
}
wp_reset_query();
}
$related_cat.= ‘</ul>’;
return $related_cat;
}
add_shortcode(‘baivietcm’, ‘bai_viet_chuyen_muc’);

Vậy là xong, giờ đây bạn muốn nó hiển thị chổ nào trong bài viết thì dùng shortcode [baivietcm] là được. Bạn có thể tham khảo bài viết trước để tự động thêm nó vào cuối mỗi bài viết.