【发布时间】: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