Hiển thị bài viết liên quan cùng danh mục trong chi tiết bài viết

clock 17:12

Dán đoạn code sau vào file single.php trong theme bạn đang sử dụng ở vị trí bạn muốn hiển thị:


<?php 
$post_id = get_the_ID();
$cat_ids = array();
$categories = get_the_category($post_id);

if ( !empty($categories) && !is_wp_error($categories) ):
    foreach ($categories as $category):
        array_push($cat_ids, $category->term_id);
    endforeach;
endif;

$current_post_type = get_post_type($post_id);

$query_args = array( 
    'category__in'      => $cat_ids,
    'post_type'         => $current_post_type,
    'post__not_in'      => array($post_id),
    'posts_per_page'    => '3', //số lượng bài viết hiển thị
    );

$related_cats_post = new WP_Query( $query_args );
?>
<?php if ( $related_cats_post->have_posts() ): ?>
    <ul>
        <?php while ( $related_cats_post->have_posts() ): $related_cats_post->the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>">
                    <?php the_title(); ?>
                </a>
                <?php the_content(); ?>
            </li>
        <?php
        endwhile;
        // Restore original Post Data
        wp_reset_postdata();
        ?>
    </ul>
<?php endif; ?>

Chúc các bạn thành công!

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất