與帖子類型不同,WordPress沒有爲分類標準slug本身的路線。
爲了使分類塞本身列出分配有分類的任何條款的所有帖子,您需要使用EXISTS
operator of tax_query
in 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;
}
}
來源
2017-06-16 12:56:25
sun
上面的例子就行了用'「分類」 =>「$ term_name''需要像這樣''taxonomy'=>「$ term_name」''雙引號引用,或者更好的不引用像'taxonomy'=> $ term_name',或者甚至更好地省略先前的賦值, 'taxonomy'=> $ term-> slug'。也就是說,使用''tax_query'=> array(...)''顯示的方法[已被棄用](http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters)。希望這可以幫助。 – MikeSchinkel 2013-05-15 00:43:53
對不起,延遲...你是對的。我相應地修改了我的答案:) – 2013-06-22 22:45:55
非常好!我希望我們一起努力幫助他人。 – MikeSchinkel 2013-06-23 04:37:56