从相同类别中获取 wordpress 帖子

Get wordpress posts from the same categories

我需要在单个 wordpress post 上输出与当前 post 具有相同类别的 post 列表。使用下面的代码,我只获得了第一类中的所有 post。如何从 post 的所有类别中获取 post(有些 post 有 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; ?>

只需使用wp_get_post_categories()函数获取当前post的类别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();

Try this code.

<?php   
    global $post;
    $categories_id = array();
    $current_category = get_the_category();
    foreach($current_category as $cc){
        $categories_id[] = $cc->term_id;
    }
    $same_category = new WP_Query(array(
        'cat'            => $categories_id,
        'post__not_in'   => array($post->ID),
        'orderby' => 'date',
        'order' => 'DESC',
        'posts_per_page' => -1,
    ));
?>