Code hiển thị bài viết liên quan trong WordPress

5/5 - (1 bình chọn)

Code hiển thị bài viết liên quan trong WordPress, , đây là code chuẩn không cần dùng Plugin nhằm tối ưu khi thiết kế wordpress

Code bài viết liên quan

Trước tiên là code bài viết liên quan. Cái này sẽ hiển thị các bài viết trong cùng một tags. Các bạn copy và paste vào file single.php và vào chỗ muốn hiển thị nhé

<?php

$tags = wp_get_post_tags(get_the_ID());

if ($tags){

    echo '<div id="relatedpost">';

    $tag_ids = array();

    foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;




    $args=array(

        'tag__in' => $tag_ids,

        'post__not_in' => array(get_the_ID()),

        'posts_per_page' => 3,

    );

    $my_query = new wp_query($args);

    if( $my_query->have_posts() ):

        echo '<ul>';

        while ($my_query->have_posts()):$my_query->the_post();

            ?>

            <li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>

            <?php

        endwhile;

        echo '</ul>';

    endif;

    wp_reset_query();

    echo '</div>';

}

?>

Code hiển thị các bài trong cùng một categorys

Và đây là code hiển thị các bài trong cùng một categorys. Các bạn cũng làm như trên nha.

<?php

$categories = get_the_category(get_the_ID());

if ($categories){

echo '<div class="relatedcat">';

$category_ids = array();

foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;

$args=array(

'category__in' => $category_ids,

'post__not_in' => array(get_the_ID()),

'posts_per_page' => 5, // So bai viet dc hien thi

);

$my_query = new wp_query($args);

if( $my_query->have_posts() ):

echo '<h3>Các tin khác</h3><ul>';

while ($my_query->have_posts()):$my_query->the_post();

?>

<li><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>

<?php

endwhile;

echo '</ul>';

endif; wp_reset_query();

echo '</div>';

}

?>

Bây giờ các bạn thêm css vào cho nó đẹp thôi. Cái này các bạn tự thêm nha. Mỗi người một mẫu thẩm mỹ mà. hi

5/5 - (1 bình chọn)


Trả lời