我有点拘泥于自定义查询。
基本上,我有一个查询,得到相关的"公司"(最多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,并在不满足条件的情况下继续。
一个更好的方法是取消中断并使用while语句
<?php while ( $query->have_posts() && $count < 3 ) : $query->the_post(); ?>