@ClemC我通过添加一个WP\\u查询来查询帖子并检查计数,从而解决了这个问题,下面是我的代码:
$term_id = get_queried_object()->term_id;
$taxonomy_name = \'product_range\';
$custom_terms = get_term_children( $term_id, $taxonomy_name );
echo \'<div class="row row__condensed">\';
foreach($custom_terms as $custom_term) {
$term = get_term_by( \'id\', $custom_term, $taxonomy_name );
wp_reset_query();
$args = array(
\'post_type\' => \'product\',
\'posts_per_page\' => 1,
\'tax_query\' => array(
array(
\'taxonomy\' => \'product_range\',
\'field\' => \'slug\',
\'terms\' => $term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
// If only one post exists link to product
if($term->count === 1 ) {
echo \'<div class="col-xs-12 col-md-4">\';
echo \'<div class="grid__item">\';
echo \'<a href="\'.get_permalink().\'">\';
echo \'</a>\';
echo \'<h3><a href="\' . get_permalink() . \'">\'.$term->name .\'</a></h3>\';
echo \'<p>\'.wp_trim_words($term->description, 23, \'...\').\'</p>\';
echo \'</div>\';
echo \'</div>\';
}
//else link to the listing page
else {
echo \'<div class="col-xs-12 col-md-4">\';
echo \'<div class="grid__item">\';
echo \'<a href="\' . get_term_link( $custom_term, $taxonomy_name ) . \'">\';
echo \'</a>\';
echo \'<h3><a href="\' . get_term_link( $custom_term, $taxonomy_name ) . \'">\'.$term->name .\'</a></h3>\';
echo \'<p>\'.wp_trim_words($term->description, 23, \'...\').\'</p>\';
echo \'</div>\';
echo \'</div>\';
}
endwhile;
}
else {
echo "no posts found.";
} //endforeach
echo \'</div>\';