A WordPress-centric search engine for devs and theme authors



get_term_by ›

Since2.3.0
Deprecatedn/a
get_term_by ( $field, $value, $taxonomy, $output = OBJECT, $filter = 'raw' )
Parameters: (5)
  • (string) $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
    Required: Yes
  • (string|int) $value Search for this term value
    Required: Yes
  • (string) $taxonomy Taxonomy Name
    Required: Yes
  • (string) $output Constant OBJECT, ARRAY_A, or ARRAY_N
    Required: No
    Default: OBJECT
  • (string) $filter Optional, default is raw or no WordPress defined filter will applied.
    Required: No
    Default: 'raw'
See:
Returns:
  • (mixed) Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
Defined at:
Codex:

Get all Term data from database by Term field and data.

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.



Source

function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
	global $wpdb;

	if ( ! taxonomy_exists($taxonomy) )
		return false;

	if ( 'slug' == $field ) {
		$field = 't.slug';
		$value = sanitize_title($value);
		if ( empty($value) )
			return false;
	} else if ( 'name' == $field ) {
		// Assume already escaped
		$value = wp_unslash($value);
		$field = 't.name';
	} else if ( 'term_taxonomy_id' == $field ) {
		$value = (int) $value;
		$field = 'tt.term_taxonomy_id';
	} else {
		$term = get_term( (int) $value, $taxonomy, $output, $filter );
		if ( is_wp_error( $term ) )
			$term = false;
		return $term;
	}

	$term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value ) );
	if ( ! $term )
		return false;

	wp_cache_add( $term->term_id, $term, $taxonomy );

	/** This filter is documented in wp-includes/taxonomy.php */
	$term = apply_filters( 'get_term', $term, $taxonomy );

	/** This filter is documented in wp-includes/taxonomy.php */
	$term = apply_filters( "get_$taxonomy", $term, $taxonomy );

	$term = sanitize_term($term, $taxonomy, $filter);

	if ( $output == OBJECT ) {
		return $term;
	} elseif ( $output == ARRAY_A ) {
		return get_object_vars($term);
	} elseif ( $output == ARRAY_N ) {
		return array_values(get_object_vars($term));
	} else {
		return $term;
	}
}