Mục tiêu:
-
Hiển thị danh sách các bài viết cùng danh mục với bài hiện tại.
-
Tự động lấy category của bài viết hiện tại.
-
Có thể đặt shortcode vào bất cứ đâu, ví dụ: trong nội dung bài viết, hoặc chèn vào file single.php của theme.
Bạn hãy chèn đoạn code sau vào file: functions.php của theme con (child theme) hoặc plugin custom functions riêng của bạn.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
// Shortcode: [related_posts] function show_related_posts_by_category($atts) { global $post; // Kiểm tra nếu không phải single post if (!is_single() || empty($post)) return ''; // Lấy danh mục của bài hiện tại $categories = wp_get_post_categories($post->ID); if (empty($categories)) return ''; // Thiết lập query $args = array( 'category__in' => $categories, 'post__not_in' => array($post->ID), 'posts_per_page' => 4, // số bài hiển thị 'orderby' => 'date', 'order' => 'DESC' ); $related_posts = new WP_Query($args); ob_start(); if ($related_posts->have_posts()) { echo '<div class="related-posts">'; echo '<h3 class="related-title">Bài viết liên quan</h3>'; echo '<div class="related-grid">'; while ($related_posts->have_posts()) { $related_posts->the_post(); ?> <div class="related-item"> <a href="<?php the_permalink(); ?>" class="related-thumb"> <?php if (has_post_thumbnail()) { the_post_thumbnail('medium'); } ?> </a> <h4 class="related-name"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> </div> <?php } echo '</div></div>'; } wp_reset_postdata(); return ob_get_clean(); } add_shortcode('related_posts', 'show_related_posts_by_category'); |
CSS gợi ý (thêm vào Customizer > CSS hoặc file style.css)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
.related-posts { margin-top: 40px; } .related-title { font-size: 20px; margin-bottom: 15px; text-transform: uppercase; } .related-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; } .related-item { text-align: center; } .related-item img { border-radius: 10px; width: 100%; height: auto; } .related-name { margin-top: 10px; font-size: 16px; } .related-name a { color: #333; text-decoration: none; } .related-name a:hover { color: #0073aa; } |
Cách dùng:
Chèn shortcode vào nội dung bài viết hoặc template:
Cách 1 – Trong nội dung: [related_posts]
Cách 2 – Trong file theme (ví dụ single.php): echo do_shortcode(‘[related_posts]’);

