get_term_by()
概述
get_term_by() 函数用于根据指定字段和值从数据库中检索分类法术语数据。它支持通过 slug、name、term_id 或 term_taxonomy_id 进行查询,并返回 WP_Term 对象或数组。
关键要点
- 函数通过 $field 和 $value 参数匹配术语,$field 可选值包括 'slug'、'name'、'term_id'(或 'id'、'ID')、'term_taxonomy_id'。
- 当 $field 为 'name' 时,$value 需自行转义;默认 $field 为 'id',但不建议使用 null。
- 如果未找到匹配术语或分类法不存在,函数返回 false;成功时返回类型由 $output 参数控制(OBJECT、ARRAY_A、ARRAY_N)。
- 此函数仅返回第一个匹配的术语,若可能匹配多个(如使用 'name' 字段),建议改用 get_terms() 以获取所有匹配项。
- 参数 $taxonomy 在 $field 为 'term_taxonomy_id' 时可选,其他情况下必需。
代码示例
// 通过名称获取分类法术语
$category = get_term_by('name', 'news', 'category');
// 通过 ID 获取术语
get_term_by('id', 12, 'category');
// 自定义分类法示例
$term = get_term_by('slug', 'playlist-key', 'wpdocs_playlist');注意事项
- 使用 'name' 字段时需注意转义 $value 值,以避免安全风险。
- 由于函数仅返回第一个匹配术语,在可能存在重复名称或 slug 的场景中,应优先使用 get_terms() 以确保获取所有相关术语。
- 自定义分类法查询必须指定 $taxonomy 参数,否则可能无法正确检索。
Gets all term data from database by term field and data.
Description
Warning: $value is not escaped for ‘name’ $field. You must do it yourself, if required.
The default $field is ‘id’, therefore it is possible to also use null for field, but not recommended that you do so.
If $value does not exist, the return value will be false. If $taxonomy exists and $field and $value combinations exist, the term will be returned.
This function will always return the first term that matches the $field– $value–$taxonomy combination specified in the parameters. If your query is likely to match more than one term (as is likely to be the case when $field is ‘name’, for example), consider using get_terms() instead; that way, you will get all matching terms, and can provide your own logic for deciding which one was intended.
See also
- sanitize_term_field(): The $context param lists the available values for get_term_by() $filter param.
Parameters
$fieldstringrequired-
Either
'slug','name','term_id'(or'id','ID'), or'term_taxonomy_id'. $valuestring|intrequired-
Search for this term value.
$taxonomystringrequired-
Taxonomy name. Optional, if
$fieldis'term_taxonomy_id'. $outputstringoptional-
The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Term object, an associative array, or a numeric array, respectively.
Default:
OBJECT $filterstringoptional-
How to sanitize term fields. Default
'raw'.
Source
function get_term_by( $field, $value, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
// 'term_taxonomy_id' lookups don't require taxonomy checks.
if ( 'term_taxonomy_id' !== $field && ! taxonomy_exists( $taxonomy ) ) {
return false;
}
// No need to perform a query for empty 'slug' or 'name'.
if ( 'slug' === $field || 'name' === $field ) {
$value = (string) $value;
if ( 0 === strlen( $value ) ) {
return false;
}
}
if ( 'id' === $field || 'ID' === $field || 'term_id' === $field ) {
$term = get_term( (int) $value, $taxonomy, $output, $filter );
if ( is_wp_error( $term ) || null === $term ) {
$term = false;
}
return $term;
}
$args = array(
'get' => 'all',
'number' => 1,
'taxonomy' => $taxonomy,
'update_term_meta_cache' => false,
'orderby' => 'none',
'suppress_filter' => true,
);
switch ( $field ) {
case 'slug':
$args['slug'] = $value;
break;
case 'name':
$args['name'] = $value;
break;
case 'term_taxonomy_id':
$args['term_taxonomy_id'] = $value;
unset( $args['taxonomy'] );
break;
default:
return false;
}
$terms = get_terms( $args );
if ( is_wp_error( $terms ) || empty( $terms ) ) {
return false;
}
$term = array_shift( $terms );
// In the case of 'term_taxonomy_id', override the provided `$taxonomy` with whatever we find in the DB.
if ( 'term_taxonomy_id' === $field ) {
$taxonomy = $term->taxonomy;
}
return get_term( $term, $taxonomy, $output, $filter );
}
Skip to note 5 content
Codex
Examples
Examples to get terms by name and taxonomy type (taxonomy_name as category, post_tag or custom taxonomy).
// Get term by name ''news'' in Categories taxonomy. $category = get_term_by('name', 'news', 'category') // Get term by name ''news'' in Tags taxonomy. $tag = get_term_by('name', 'news', 'post_tag') // Get term by name ''news'' in Custom taxonomy. $term = get_term_by('name', 'news', 'my_custom_taxonomy') // Get term by name ''Default Menu'' from theme's nav menus. // (Alternative to using wp_get_nav_menu_items) $menu = get_term_by('name', 'Default Menu', 'nav_menu');By id (term_id, not post_id):
// Get term by id (''term_id'') in Categories taxonomy. get_term_by('id', 12, 'category')Skip to note 6 content
nicoseijas
Example of retrieving a category by it’s name:
$category = get_term_by('name', 'Term Name', 'category');Output:
(object) array( 'term_id' => 49, 'name' => 'Term Name', 'slug' => 'term-name', 'term_group' => 0, 'term_taxonomy_id' => 49, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 286, 'filter' => 'raw', )Skip to note 7 content
bcworkz
get_term_by() returns a single WP_Term object. Because of core changes from v4.1 – 4.3, it’s now possible for multiple terms to match the supplied name or slug parameters. The WP_Term Object returned will be the first matching term found by mySQL, there is no indication that other matching terms may exist. If there is any possibility of multiple terms having the same name or slug in your application, you should use get_terms() instead of get_term_by() .
Skip to note 8 content
Shabti Kaplan
If you are using a custom taxonomy, this might not work unless you add the third parameter, namely the taxonomy name:
My custom taxonomy is
wpdocs_playlist.$playlist = get_term_by( 'slug', $playlist_key, 'wpdocs_playlist' );