get_term_by()
最后更新于:2021-11-27 00:55:23
get_term_by( string$field, string|int$value, string$taxonomy=”, string$output=OBJECT, string$filter=’raw’)Get all Term data from database by Term field and data.
参数
- $field
-
(string) (Required) Either ‘slug’, ‘name’, ‘id’ or ‘ID’ (term_id), or ‘term_taxonomy_id’.
- $value
-
(string|int) (Required) Search for this term value.
- $taxonomy
-
(string) (Optional) Taxonomy name. Optional, if
$field
is ‘term_taxonomy_id’.Default value: ”
- $output
-
(string) (Optional) The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a GC_Term object, an associative array, or a numeric array, respectively.
Default value: OBJECT
- $filter
-
(string) (Optional) How to sanitize term fields.
Default value: ‘raw’
响应
(GC_Term|array|false) GC_Term instance (or array) on success, depending on the $output
value. False if $taxonomy
does not exist or $term
was not found.
源文件
文件: gc-includes/taxonomy.php
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_gc_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_gc_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 );
}