首页 > 解决方案 > 按类别分类的 WordPress 相关内容为自定义帖子类型中的每个帖子产生相同的结果

问题描述

正如标题所说,我正在按类别过滤与 WordPress 相关的内容以获取自定义帖子类型。我得到了结果,但在每个帖子页面上,相关内容列表都是相同的,即使类别完全不同。我希望它能够根据类别正确显示每种帖子类型的结果。

我已经尝试了下面的代码和它的许多变体。我什至尝试过诸如 YARPP 之类的插件,但即使它们在每个页面上生成相同的帖子,无论类别如何。

        $post_id = get_the_ID();
        $cat_ids = array();
        $categories = get_the_category( $post_id );

        if(!empty($categories) && is_wp_error($categories)):
            foreach ($categories as $category):
            array_push($cat_ids, $category->term_id);
        endforeach;
        endif;

        $current_post_type = get_post_type($post_id);
        $query_args = array(

                            'category__in'   => $cat_ids,
                            'post_type'      => array($current_post_type),
                            'post__not_in'    => array($post_id),
                            'posts_per_page'  => '5',
                            'ignore_sticky_posts' => 1,
                            'orderby' => 'rand'


                            );

        $related_cats_post = new WP_Query( $query_args );

        if($related_cats_post->have_posts()):
            while($related_cats_post->have_posts()): array_push($posts, $related_cats_post->the_post());

    ?>
<ul>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
</ul>
<?php endwhile;
    return $posts;
    // Restore original Post Data
    wp_reset_postdata();
    endif;

    }

我希望上面的代码能够正常工作 - 我相信它甚至可能在某一时刻正常工作。我只是想知道是否有任何可能导致相关帖子列表在每个帖子上都相同?

标签: phpwordpress

解决方案


推荐阅读