在…内get_posts()
属于WP_Query
类,您将看到此代码块。
/*
* Ensure that \'taxonomy\', \'term\', \'term_id\', \'cat\', and
* \'category_name\' vars are set for backward compatibility.
*/
if ( ! empty( $this->tax_query->queried_terms ) ) {
/*
* Set \'taxonomy\', \'term\', and \'term_id\' to the
* first taxonomy other than \'post_tag\' or \'category\'.
*/
if ( ! isset( $q[\'taxonomy\'] ) ) {
foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
if ( empty( $queried_items[\'terms\'][0] ) ) {
continue;
}
if ( ! in_array( $queried_taxonomy, array( \'category\', \'post_tag\' ) ) ) {
$q[\'taxonomy\'] = $queried_taxonomy;
if ( \'slug\' === $queried_items[\'field\'] ) {
$q[\'term\'] = $queried_items[\'terms\'][0];
} else {
$q[\'term_id\'] = $queried_items[\'terms\'][0];
}
// Take the first one we find.
break;
}
}
}
// \'cat\', \'category_name\', \'tag_id\'
foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
if ( empty( $queried_items[\'terms\'][0] ) ) {
continue;
}
if ( \'category\' === $queried_taxonomy ) {
$the_cat = get_term_by( $queried_items[\'field\'], $queried_items[\'terms\'][0], \'category\' );
if ( $the_cat ) {
$this->set( \'cat\', $the_cat->term_id );
$this->set( \'category_name\', $the_cat->slug );
}
unset( $the_cat );
}
if ( \'post_tag\' === $queried_taxonomy ) {
$the_tag = get_term_by( $queried_items[\'field\'], $queried_items[\'terms\'][0], \'post_tag\' );
if ( $the_tag ) {
$this->set( \'tag_id\', $the_tag->term_id );
}
unset( $the_tag );
}
}
}
正如你在第二个
foreach
回路,用于
category
在分类法中,WordPress仅使用第一个查询的术语从中提取slug,然后将其设置为
query_vars
. 同样的情况也发生在
post_tag
.
WordPress为什么这么做,评论已经说明了一切。