Advertisements

term_exists

Definition:
function term_exists($term, $taxonomy = '', $parent = 0) {}

Check if Term exists.
Returns the index of a defined term, or 0 (false) if the term doesn’t exist.

Parameters

  • int|string $term: The term to check
  • string $taxonomy: The taxonomy name to use
  • int $parent: ID of parent term under which to confine the exists search.

Return values

returns:Get the term id or Term Object, if exists.

Source code

function term_exists($term, $taxonomy = '', $parent = 0) {

	global $wpdb;



	$select = "SELECT term_id FROM $wpdb->terms as t WHERE ";

	$tax_select = "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE ";



	if ( is_int($term) ) {

		if ( 0 == $term )

			return 0;

		$where = 't.term_id = %d';

		if ( !empty($taxonomy) )

			return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );

		else

			return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );

	}



	$term = trim( stripslashes( $term ) );



	if ( '' === $slug = sanitize_title($term) )

		return 0;



	$where = 't.slug = %s';

	$else_where = 't.name = %s';

	$where_fields = array($slug);

	$else_where_fields = array($term);

	if ( !empty($taxonomy) ) {

		$parent = (int) $parent;

		if ( $parent > 0 ) {

			$where_fields[] = $parent;

			$else_where_fields[] = $parent;

			$where .= ' AND tt.parent = %d';

			$else_where .= ' AND tt.parent = %d';

		}



		$where_fields[] = $taxonomy;

		$else_where_fields[] = $taxonomy;



		if ( $result = $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s", $where_fields), ARRAY_A) )

			return $result;



		return $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s", $else_where_fields), ARRAY_A);

	}



	if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )

		return $result;



	return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );

}

2941

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: