Shortcode bài viết liên quan theo chuyên mục / tag trong WordPress

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 Vũ Trụ Số có 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 theo chuyên mục 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 vutruso_related_posts_by_cat() {
    // Get categories of the current post
    $categories = get_the_category(get_the_ID());

    // Extract category IDs
    $category_ids = array();
    foreach($categories as $category) $category_ids[] = $category->term_id;

    // Define query arguments
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => '10',
        'post__not_in' => array(get_the_ID()), // Exclude current post
        'category__in' => $category_ids, // Fetch posts that are in the same categories as the current post
        'orderby' => 'rand' // Random order
    );

    $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 = 'Không có bài viết nào phù hợp';
    endif;

    return $output;
}
add_shortcode('vutruso_related_posts', 'vutruso_related_posts_by_cat');

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

  • post_type Chỉ định post_type được truy xuất, không phải các trang hoặc loại bài đăng tùy chỉnh.
  • posts_per_page Đặt giới hạn về số lượng bài đăng để truy xuất là 10.
  • post__not_in Loại trừ bài viết hiện tại khỏi kết quả.
  • orderby Được đặt thành rand có nghĩa là các bài viết được sắp xếp ngẫu nhiên.

Sau khi thêm code trên vào file functions.php bạn có thể sử dụng shorcode [vutruso_related_posts_by_cat] để 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('[vutruso_related_posts_by_cat]'); ?>

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}

Đây là thành quả sau khi bạn thêm code.

Shortcode lấy bài viết liên quan theo tag trong WordPress

Bạn cũng có thể lấy bài viết liên quan theo tag bằng code dưới đây.

function vutruso_related_posts_by_tag() {
    // Get tags of the current post
    $tags = wp_get_post_tags(get_the_ID());

    // Extract tag IDs
    $tag_ids = array();
    foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;

    // Define query arguments
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => '10',
        'post__not_in' => array(get_the_ID()), // Exclude current post
        'tag__in' => $tag_ids, // Fetch posts that have the same tags as the current post
        'orderby' => 'rand' // Random order
    );

    $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 = 'No related posts found.';
    endif;

    return $output;
}
add_shortcode('vutruso_related_posts_by_tag', 'vutruso_related_posts_by_tag');

Dùng shortcode [vutruso_related_posts_by_tag]

Tuỳ 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.

Ngoài ra, Dựa vào 2 Shortcode lấy và hiển thị bài viết liên quan theo chuyên mục / tag trong WordPress như trên bạn cũng có thể phát triển thêm tính năng ví dụ, nếu bài viết có tag thì hiển thị bài viết liên quan theo từ khoá, nếu bài viết không có tag nào cả thì sẽ cho hiển thị bài viết liên quan theo chuyên mục (category). Ngoài ra bạn cũng có thể code để lấy ảnh đại diện nữa cho nó đẹp chẳng hạn.

Cảm ơn đã đọc bài viết.

Nếu bạn thấy bài viết có ích hãy sao chép link và chia sẻ bài viết
daotiendung

Tiến Dũng Đào chuyên quản lý, vận hành các dịch vụ website. Anh có nhiều năm kinh nghiệm về VPS, Hosting, technical SEO, CMS. Đặc biệt yêu thích WordPress với hơn 5 năm phát triển theme và plugin. Sở thích của anh là đọc, viết blog, đi du lịch, tập võ và chia sẻ các kiến thức cho mọi người.

Bài viết liên quan