функция since 2.3.0

get_term_by()

Проверено на WordPress 6.9, обновлено Источник: WordPress Developer Resources.

Сигнатура

get_term_by( string $field, string|int $value, string $taxonomy = '', string $output = OBJECT, string $filter = 'raw' ): WP_Term|array|false

Описание

Предупреждение: $value не экранируется для $field «name». При необходимости вы должны сделать это сами.
Поле $field по умолчанию равно «id», поэтому для field можно также использовать null, но это не рекомендуется.
Если $value не существует, возвращаемым значением будет false. Если $taxonomy существует и существуют сочетания $field и $value, термин будет возвращён.
Эта функция всегда возвращает первый термин, соответствующий сочетанию $field– $value–$taxonomy, указанному в параметрах. Если ваш запрос, вероятно, совпадёт более чем с одним термином (что вероятно, например, когда $field равно «name»), используйте вместо этого get_terms(); так вы получите все совпадающие термины и сможете задать собственную логику выбора нужного.
См. alsosanitize_term_field(): параметр $context перечисляет доступные значения для параметра get_term_by() $filter.

Оригинал (английский)

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

Параметры

$field string обязательный
Либо 'slug', 'name', 'term_id' (или 'id', 'ID'), либо 'term_taxonomy_id'.
$value string|int обязательный
Искать по этому значению термина.
$taxonomy string необязательный = ''
Имя таксономии. Необязательно, если $field равно 'term_taxonomy_id'.
$output string необязательный = OBJECT
Требуемый тип возврата. Один из OBJECT, ARRAY_A или ARRAY_N, что соответствует объекту WP_Term, ассоциативному массиву или числовому массиву соответственно.
$filter string необязательный = 'raw'
Как очищать поля термина. Значение по умолчанию 'raw'.

Возвращаемое значение

WP_Term|array|false

WP_Term $output $taxonomy $term

Исходный код

wp-includes/taxonomy.php:1099

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 );
}

История изменений

ВерсияОписание
5.5.0 Added 'ID' as an alias of 'id' for the $field parameter.
4.4.0 $taxonomy is optional if $field is 'term_taxonomy_id'. Converted to return a WP_Term object if $output is OBJECT.
2.3.0 Introduced.

Что будем искать? Например,Продвижение

Этот сайт использует куки-файлы. Оставаясь на сайте, Вы соглашаетесь на их использование. Для получения дополнительной информации, пожалуйста, ознакомьтесь с политикой в отношении персональных данных.