如何在自定义帖子中显示帖子类别的相关帖子

时间:2021-09-17 作者:Ricardio

我们创建了一个名为“Handbook”的自定义posttype,它有自己的类别。在本手册类别中,我们有“fase 1”、“fase 2”等类别。此posttype中的所有帖子都选择了其中一个类别(fase 1等)。在这个帖子类型的所有帖子上,我需要一个有相同类别的相关帖子的部分。

为此,我使用了以下代码;

function ms_related_kb() {

    $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\'      => $current_post_type,
        \'post__not_in\'    => array($post_id),
        \'posts_per_page\'  => \'5\'

     );

    $related_cats_post = new WP_Query( $query_args );
    

    if($related_cats_post->have_posts()):
         while($related_cats_post->have_posts()): $related_cats_post->the_post();
            $postIcon = get_field(\'artikel_icon\');
            $postsList .= \'<li class="kb-related-item"><a href="\' . get_the_permalink() . \'" class="kb-related-link"><div class="kb-related-box"><img src="\' . $postIcon[url] . \'" alt="ALT" class="kb-related-image"><p class="kb-related-title">\' . get_the_title() . \'</p></div></a></li>\';
        endwhile;
    
        return \'<ul class="kb-related-list">\' . $postsList . \'</ul>\';

        // Restore original Post Data
        wp_reset_postdata();
     endif;
}
add_shortcode(\'ms_related_kennisartikelen\', \'ms_related_kb\');
问题是,有了这段代码,我就得到了完整posttype“手册”的所有相关帖子。我需要更改什么才能获得类别的所有相关帖子,而不是帖子类型?

1 个回复
SO网友:Hitesh Gandhi

@李嘉图·德潘宁I think you are going on wrong direction. You just want to get only those posts which is related to current category right?

If yes then you need to filter post using tax_query like below.

$args = array(
    \'post_type\' => \'post\',
    \'tax_query\' => array(
        array(
            \'taxonomy\' => \'category\',
            \'field\'    => \'term_id\',
            \'terms\'    => array($cat_ids),
            \'operator \' => \'IN\',
        ),
    ),
);
$query = new WP_Query( $args );

相关推荐

如何从unction.php中排除Get_Categories返回的类别?

我有一个插件,可以创建我的网站地图。它首先获取所有类别get_categories 然后获取每个页面的所有页面。但是,我有一个类别不能包含在插件代码中:$args[\'exclude\']=2; $cats = get_categories( $args ); 问题是,如果插件替换文件,我的修改将被删除,我尝试了以下方法:function exclude_cat($taxonomy, $args) { $args[\'exclude\']=2;