【问题标题】:If a Wordpress query with taxonomy has less than X fill with another query如果带有分类的 Wordpress 查询少于 X 填充另一个查询
【发布时间】:2016-03-23 23:14:50
【问题描述】:

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

基本上,我有一个查询可以获取帖子的相关“公司”(最多 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 wordpress loops count taxonomy


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 2011-12-02
      • 2020-09-22
      • 2014-08-18
      • 1970-01-01
      相关资源
      最近更新 更多