Tribe__Repository::where_meta_related_by( string|array $meta_keys, string $compare, string $field = null, string|array $values = null )

Filters the query to only return posts that are related, via a meta key, to posts that satisfy a condition.


Parameters

$meta_keys

(string|array) (Required) One or more meta_keys relating the queried post type(s) to another post type.

$compare

(string) (Required) The SQL comparison operator.

$field

(string) (Optional) One (a column in the posts table) that should match the comparison criteria; required if the comparison operator is not EXISTS or NOT EXISTS.

Default value: null

$values

(string|array) (Optional) One or more values the post field(s) should be compared to; required if the comparison operator is not EXISTS or NOT EXISTS.

Default value: null


Top ↑

Return

($this)


Top ↑

Source

File: src/Tribe/Repository.php

	public function where_meta_related_by( $meta_keys, $compare, $field = null, $values = null ) {
		$meta_keys = Tribe__Utils__Array::list_to_array( $meta_keys );

		if ( ! in_array( $compare, array( 'EXISTS', 'NOT EXISTS' ) ) ) {
			if ( empty( $field ) || empty( $values ) ) {
				throw Tribe__Repository__Usage_Error::because_this_comparison_operator_requires_fields_and_values( $meta_keys, $compare, $this );
			}
			$field = esc_sql( $field );
		}

		/** @var wpdb $wpdb */
		global $wpdb;
		$p  = $this->sql_slug( 'meta_related_post', $compare, $meta_keys );
		$pm = $this->sql_slug( 'meta_related_post_meta', $compare, $meta_keys );

		$this->filter_query->join( "LEFT JOIN {$wpdb->postmeta} {$pm} ON {$wpdb->posts}.ID = {$pm}.post_id" );
		$this->filter_query->join( "LEFT JOIN {$wpdb->posts} {$p} ON {$pm}.meta_value = {$p}.ID" );

		$keys_in = $this->prepare_interval( $meta_keys );

		if ( 'EXISTS' === $compare ) {
			$this->filter_query->where( "{$pm}.meta_key IN {$keys_in} AND {$pm}.meta_id IS NOT NULL" );
		} elseif ( 'NOT EXISTS' === $compare ) {
			$this->filter_query->where( "{$pm}.meta_id IS NULL" );
		} else {
			if ( in_array( $compare, self::$multi_value_keys, true ) ) {
				$values = $this->prepare_interval( $values );
			} else {
				$values = $this->prepare_value( $values );
			}
			$this->filter_query->where( "{$pm}.meta_key IN {$keys_in} AND {$p}.{$field} {$compare} {$values}" );
		}

		return $this;
	}