1) 解决这个问题非常简单-我将类别名称请求包装在if have_posts
这样就消除了空值
2) 我必须使用\'operator\' => \'NOT IN\'
列出不在分类中的处理方法。
我确信有一种更精简、更好的方法来做以下事情,但现在这正是我想要做的。
最终代码
<?php
// grab current page info
$queried_object = get_queried_object();
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;
// fetch the terms for brands tax
$terms = get_terms( \'brands\', array(
\'orderby\' => \'title\',
\'order\' => \'ASC\',
\'hide_empty\' => true,
\'posts_per_page\' => -1,
) );
the_archive_title( \'<h1 class="page-title">\', \'</h1>\' );
// now run a query for each brand
foreach( $terms as $term ) {
$args = array(
\'post_type\' => \'treatments\',
\'nopaging\' => true,
\'orderby\' => \'title\',
\'order\' => \'ASC\',
\'hide_empty\' => true,
\'posts_per_page\' => -1,
\'tax_query\' => array(
array(
\'taxonomy\' => \'brands\',
\'terms\' => $term->slug,
\'field\' => \'slug\',
\'operator\' => \'IN\',
\'hide_empty\' => true,
),
array(
\'relation\' => \'OR\',
array(
\'taxonomy\' => \'beautysalon\',
\'terms\' => $queried_object->slug,
\'field\' => \'slug\',
\'operator\' => \'IN\'
),
array(
\'taxonomy\' => \'skinclinic\',
\'terms\' => $queried_object->slug,
\'field\' => \'slug\',
\'operator\' => \'IN\'
),
array(
\'taxonomy\' => \'spadays\',
\'terms\' => $queried_object->slug,
\'field\' => \'slug\',
\'operator\' => \'IN\'
),
)
)
);
$query = new WP_Query( $args );
// only show a header if there is posts present
if( $query->have_posts() ) :
echo\'<h2>\' . $term->name . \'</h2>\';
echo \'<ul>\';
while ( $query->have_posts() ) :
$query->the_post(); ?>
<li id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile;
echo \'</ul>\';
endif;
wp_reset_postdata();
}
// second query - everything not in a brand
$args = array(
\'post_type\' => \'treatments\',
\'nopaging\' => true,
\'orderby\' => \'title\',
\'order\' => \'ASC\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'brands\',
\'terms\' => $term->slug,
\'field\' => \'term_id\',
\'operator\' => \'NOT IN\',
),
array(
\'relation\' => \'OR\',
array(
\'taxonomy\' => \'beautysalon\',
\'terms\' => $queried_object->slug,
\'field\' => \'slug\',
\'operator\' => \'IN\'
),
array(
\'taxonomy\' => \'skinclinic\',
\'terms\' => $queried_object->slug,
\'field\' => \'slug\',
\'operator\' => \'IN\'
),
array(
\'taxonomy\' => \'spadays\',
\'terms\' => $queried_object->slug,
\'field\' => \'slug\',
\'operator\' => \'IN\'
),
)
));
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
echo \'<h2>Other \' . $queried_object->name . \' Treatments</h2>\';
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<li id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile;
endif;
echo \'</ul>\';
wp_reset_postdata();
?>