与帖子类型不同,WordPress 没有分类 slug 本身的路径。
要使分类 slug 本身列出所有分配有任何分类术语的帖子,您需要使用 in 的运算EXISTS
符tax_query
WP_Query
:
// Register a taxonomy 'location' with slug '/location'.
register_taxonomy('location', ['post'], [
'labels' => [
'name' => _x('Locations', 'taxonomy', 'mydomain'),
'singular_name' => _x('Location', 'taxonomy', 'mydomain'),
'add_new_item' => _x('Add New Location', 'taxonomy', 'mydomain'),
],
'public' => TRUE,
'query_var' => TRUE,
'rewrite' => [
'slug' => 'location',
],
]);
// Register the path '/location' as a known route.
add_rewrite_rule('^location/?$', 'index.php?taxonomy=location', 'top');
// Use the EXISTS operator to find all posts that are
// associated with any term of the taxonomy.
add_action('pre_get_posts', 'pre_get_posts');
function pre_get_posts(\WP_Query $query) {
if (is_admin()) {
return;
}
if ($query->is_main_query() && $query->query === ['taxonomy' => 'location']) {
$query->set('tax_query', [
[
'taxonomy' => 'location',
'operator' => 'EXISTS',
],
]);
// Announce this custom route as a taxonomy listing page
// to the theme layer.
$query->is_front_page = FALSE;
$query->is_home = FALSE;
$query->is_tax = TRUE;
$query->is_archive = TRUE;
}
}