首页 > 解决方案 > 获取来自相同类别的 wordpress 帖子

问题描述

我需要在单个 wordpress 帖子上输出与当前帖子具有相同类别的帖子列表。使用下面的代码,我只有第一类的所有帖子。如何从所有帖子的类别中获取帖子(有些帖子有 2 个或更多类别)。

            <?php   
                global $post;
                $current_category = get_the_category();

                $same_category = new WP_Query(array(
                    'cat'            => $current_category[0]->cat_ID,
                    'post__not_in'   => array($post->ID),
                    'orderby' => 'date',
                    'order' => 'DESC',
                    'posts_per_page' => -1,
                ));

            ?>

            <?php while ( $same_category->have_posts() ) : $same_category->the_post(); ?>
                <li>
                    <div class="borderline">
                        <a href="<?php the_permalink(); ?>">
                            <?php the_title(); ?>
                        </a>
                    </div>
                </li>
            <?php endwhile; ?>

标签: phpwordpressposts

解决方案


只需使用该wp_get_post_categories()函数获取当前帖子的类别 ID,然后category__in在查询中使用。

get_header();

    while ( have_posts() ) {
        the_post();

        // Show current posts info
        the_title();
        the_content();

        // Show posts of current post categories
        $post_id = get_the_ID();
        $post_categories = wp_get_post_categories( $post_id );

        $query_args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'category__in' => $post_categories,
        );

        $query_res = new WP_Query($query_args);

        if ( $query_res->have_posts() ) {

            while ( $query_res->have_posts() ) {

                $query_res->the_post();

                the_title();
            }

        } else {

            echo 'Nothing to show!';
        }

        wp_reset_postdata();

    }

get_footer();

推荐阅读