Những đoạn code hay dùng trong lập trình theme WordPress (Phần 11: Code bài viết liên quan)

Những đoạn code hay dùng trong lập trình theme WordPress (Phần 11: Code bài viết liên quan)

28/01/2023 - 78

11.Code bài viết liên quan

Hiển thị bài viết liên quan theo tag

<!-- Hiển thị bài viết theo Tag -->
<div id="relatedposttags"> 
    <?php
        $tags = wp_get_post_tags($post->ID);
        if ($tags) 
        {
            $tag_ids = array();
            foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
// lấy danh sách các tag liên quan
            $args=array(
            'tag__in' => $tag_ids,
            'post__not_in' => array($post->ID), // Loại trừ bài viết hiện tại
            'showposts'=>5, // Số bài viết bạn muốn hiển thị.
            'caller_get_posts'=>1
            );
            $my_query = new wp_query($args);
            if( $my_query->have_posts() ) 
            {
                echo '<h3>Bài viết liên quan</h3><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
                }
                echo '</ul>';
            }
        }
    ?>
</div>

Hiển thị vài viết liên quan theo category

<?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, // Số bài viết bạn muốn hiển thị.
        'caller_get_posts'=>1
        );
        $my_query = new wp_query($args);
        if( $my_query->have_posts() ) 
        {
            echo '<h3>Bài viết liên quan</h3><ul class="list-news">';
            while ($my_query->have_posts())
            {
                $my_query->the_post();
                ?>
                <li>
                    <div class="new-img"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(array(85, 75)); ?></a></div>
                    <div class="item-list">
                        <h4><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4>
                         <?php the_excerpt(); ?>
                    </div>
                 </li>
                 <?php
            }
            echo '</ul>';
        }
    }
?>

2 đoạn code này thường được đặt dưới nội dung bài viết, tức phần dưới của file single.php

Trả lời

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 *

Bài viết liên quan
Contact Me on Zalo