如果具有分类法的 Wordpress 查询少于 X,则用另一个查询填充

If a Wordpress query with taxonomy has less than X fill with another query

我有点卡在自定义查询上。

基本上我有一个查询与 post 的 "companies"(最多 3 个)相关。如果查询没有 3,则使用另一个查询来填充空格(最多 3 个)。我似乎无法让它做它应该做的事情。目前显示 6???不太确定哪里出错了!

$taxonomy = 'company';

// Get the post company
$terms = wp_get_post_terms( $the_post_id, $taxonomy );

$term_name = $terms[0]->name;

// Query for the related posts based on the company
$taxonomy_query = new WP_Query( array(

'tax_query' => array(
    array(
        'taxonomy' => $taxonomy,
        'field' => 'name',
        'terms'    => $term_name,
    ),
),
'post_type'=> 'post',
'post__not_in' => array($the_post_id),
'posts_per_page' => 3
) );

// Query for the non-related posts (use to fill the empty spaces)
$query = new WP_Query( array(

'category_name' => $cat_name,
'post_type'=> 'post',
'post__not_in' => array($the_post_id),
'posts_per_page' => 3
) );

然后我得到上述查询的输出

<div class="l-row">

    <?php $count = 0; ?>

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

        <?php while ( $taxonomy_query->have_posts() ) : $taxonomy_query->the_post(); ?>

        <?php $related_posts = get_post(); ?>

        <?php $count++; ?>

        <div class="l-col-sm-4">

            <?php _module( 'tile', array(
                 'post'    => $related_posts,
                 'image'   => true,
                 'excerpt' => false
             ) ); ?>
        </div>

        <?php endwhile; ?>

    <?php endif; ?>

    <?php wp_reset_query(); ?>

    // New query to fill if the above query doesn't add up to 3

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

        <?php while ( $query->have_posts() ) : $query->the_post(); ?>

        <?php $related_posts = get_post(); ?>

        <?php $count++; ?>

        <div class="l-col-sm-4">

            <?php _module( 'tile', array(
                'post'    => $related_posts,
                'image'   => true,
                'excerpt' => false
            ) ); ?>

         </div>

        <?php if($count == 3) {
            break;
        } ?>

        <?php endwhile; ?>

    <?php endif; ?>

    <?php wp_reset_query(); ?>

</div>

如果有人能指出正确的方向,请提前致谢!

你的问题在这里(假设你的代码有效)

<?php if($count == 3) {
        break;
    } ?>

如果您在第一个查询中有 3 个帖子,您的计数是 3,您在上述语句之前的第 4 个增加计数,现在它等于 4,并且在不满足您的条件的情况下继续。

更好的方法是放弃 break 并使用 while 语句

  <?php while ( $query->have_posts() && $count < 3 ) : $query->the_post(); ?>