Hiển thị các bài viết liên quan theo tag, theo category trong wordpress

Bai Viet Lien Quan

Chào các bạn!

Hôm nay mình xin được chia sẻ code hiển thị bài viết liên quan (Theo tags) và bài viết cùng chuyên mục (Trong categorys) không cần dùng đến plugin. Rất tốt cho ai muốn làm theme và không muốn dùng quá nhiều pugin.

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)
{
    $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()),
        'showposts'=>5,
        'ignore_sticky_posts'=>1
    );
    $my_query = new wp_query($args);
    if( $my_query->have_posts() )
    {
        echo '<h3 class="title-related-post">'.esc_html__('Bài viết liên quan','flatsome').'</h3><ul class="news-related">';
        while ($my_query->have_posts())
        {
            $my_query->the_post();
            ?>
            <li>
                <a href="<?php the_permalink(); ?>">
                <div class="new-img"><?php the_post_thumbnail('thumbnail'); ?></div>
                    <h4><?php the_title(); ?></h4>
                </a>
            </li>
            <?php
        }
        echo '</ul>';
    }
}
wp_reset_query();
?>

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($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'=>5,
        'ignore_sticky_posts'=>1
    );
    $my_query = new wp_query($args);
    if( $my_query->have_posts() )
    {
        echo '<h3 class="title-related-post">'.esc_html__('Bài viết liên quan','flatsome').'</h3><ul class="news-related">';
        while ($my_query->have_posts())
        {
            $my_query->the_post();
            ?>
            <li>
                <a href="<?php the_permalink(); ?>">
                <div class="new-img"><?php the_post_thumbnail('thumbnail'); ?></div>
                    <h4><?php the_title(); ?></h4>
                </a>
            </li>
            <?php
        }
        echo '</ul>';
    }
}
wp_reset_query();
?>

 

Related Post

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

0336931028
Facebook Skype Youtube Chat FB