仅当匹配所有类别时才显示帖子

时间:2020-10-29 作者:Tanvir

我有多个不同类别的帖子,包括一个名为;视频“;,现在,我试图只显示和主帖子的所有类别相匹配的帖子,包括“common”;视频“;类别

假设主要岗位有:Catagory A, Catagory B, Videos

输出帖子必须与以下类别匹配:

Catagory A, Catagory B, Videos (输出1)

Catagory A, Catagory B, Videos (输出2)

Catagory A, Catagory B, Videos (输出3)。。。

使用以下代码,它将显示来自;视频“;类别:

<?php $orig_post = $post;
    global $post;
    $categories = get_the_category($post->ID);
    if ($categories) {
    $category_ids = array();
    foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
    $args=array(
    \'post__not_in\' => array($post->ID),
    \'posts_per_page\'=> 30,
    \'tax_query\' => array( array(
        \'taxonomy\' => \'post_format\',
        \'field\' => \'slug\',
        \'terms\' => array(\'post-format-video\'),
        \'operator\' => \'IN\'
       ) )
    );
    $my_query = new WP_Query( $args );
    if( $my_query->have_posts() ) {?>
<div class="sidebar">
    <?php while( $my_query->have_posts() ) { $my_query->the_post();?>

1 个回复
SO网友:Dave Romsey

这里是您的代码的更新版本,它将获得具有Post格式的PostVideo 与循环中当前帖子的类别相同。

你会打电话的wpse_get_video_posts_with_matching_categories() 执行该功能。

function wpse_get_video_posts_with_matching_categories() {
    $categories = get_the_category( get_the_ID() );

    if ( empty ( $categories ) ) {
        return;
    }

    $my_query = new WP_Query( [
        \'post__not_in\'   => [ get_the_ID() ],
        \'posts_per_page\' => 30,
        \'tax_query\'      => [
            \'relation\' => \'AND\', // We will check BOTH of the following criteria.
            [
                \'taxonomy\' => \'post_format\',
                \'field\'    => \'slug\',
                \'terms\'    => [ \'post-format-video\' ],
                \'operator\' => \'IN\',
            ],
            [
                \'taxonomy\' => \'category\',
                \'field\'    => \'term_id\',
                \'terms\'    => wp_list_pluck( $categories, \'term_id\' ), // A handy way to extract data.
                \'operator\' => \'AND\',
            ],
        ],
    ] );
    ?>

    <?php if ( $my_query->have_posts() ) : ?>

    <div class="sidebar">
        <?php while( $my_query->have_posts() ) : ?>
            <?php
                $my_query->the_post();
                // Output content...
                the_title( \'<h3>\', \'</h3>\' );
            ?>
        <?php endwhile; ?>
    </div>
    <?php wp_reset_postdata(); ?>
    <?php endif; ?>
    <?php
}
我测试了这个,我想这就是你想要的。请注意,您的原始代码缺少我们对术语ID进行查询的部分。我还用一些最佳实践把事情弄得井井有条。