Advertisements

get_term_by

Definition:
function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {}

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.

Parameters

  • string $field: Either ‘slug’, ‘name’, or ‘id’
  • string|int $value: Search for this term value
  • string $taxonomy: Taxonomy Name
  • string $output: Constant OBJECT, ARRAY_A, or ARRAY_N
  • string $filter: Optional, default is raw or no WordPress defined filter will applied.

Return values

returns:Term Row from database. Will return false if $taxonomy does not exist or $term was not found.

Defined filters

  • get_term
    apply_filters('get_term', $term, $taxonomy)
  • get_$taxonomy
    apply_filters("get_$taxonomy", $term, $taxonomy)

Source code

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 = stripslashes($value);

		$field = 't.name';

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



	$term = apply_filters('get_term', $term, $taxonomy);

	$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;

	}

}

1753

Advertisements

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: