[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-meta-query.php (source)

   1  <?php
   2  /**
   3   * Meta API: WP_Meta_Query class
   4   *
   5   * @package WordPress
   6   * @subpackage Meta
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Core class used to implement meta queries for the Meta API.
  12   *
  13   * Used for generating SQL clauses that filter a primary query according to metadata keys and values.
  14   *
  15   * WP_Meta_Query is a helper that allows primary query classes, such as WP_Query and WP_User_Query,
  16   *
  17   * to filter their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached
  18   * to the primary SQL query string.
  19   *
  20   * @since 3.2.0
  21   */
  22  #[AllowDynamicProperties]
  23  class WP_Meta_Query {
  24      /**
  25       * Array of metadata queries.
  26       *
  27       * See WP_Meta_Query::__construct() for information on meta query arguments.
  28       *
  29       * @since 3.2.0
  30       * @var array
  31       */
  32      public $queries = array();
  33  
  34      /**
  35       * The relation between the queries. Can be one of 'AND' or 'OR'.
  36       *
  37       * @since 3.2.0
  38       * @var string
  39       * @phpstan-var 'AND'|'OR'|null
  40       */
  41      public $relation;
  42  
  43      /**
  44       * Database table to query for the metadata.
  45       *
  46       * @since 4.1.0
  47       * @var string
  48       */
  49      public $meta_table;
  50  
  51      /**
  52       * Column in meta_table that represents the ID of the object the metadata belongs to.
  53       *
  54       * @since 4.1.0
  55       * @var string
  56       */
  57      public $meta_id_column;
  58  
  59      /**
  60       * Database table that where the metadata's objects are stored (eg $wpdb->users).
  61       *
  62       * @since 4.1.0
  63       * @var string
  64       */
  65      public $primary_table;
  66  
  67      /**
  68       * Column in primary_table that represents the ID of the object.
  69       *
  70       * @since 4.1.0
  71       * @var string
  72       */
  73      public $primary_id_column;
  74  
  75      /**
  76       * A flat list of table aliases used in JOIN clauses.
  77       *
  78       * @since 4.1.0
  79       * @var array
  80       */
  81      protected $table_aliases = array();
  82  
  83      /**
  84       * A flat list of clauses, keyed by clause 'name'.
  85       *
  86       * @since 4.2.0
  87       * @var array
  88       */
  89      protected $clauses = array();
  90  
  91      /**
  92       * Whether the query contains any OR relations.
  93       *
  94       * @since 4.3.0
  95       * @var bool
  96       */
  97      protected $has_or_relation = false;
  98  
  99      /**
 100       * Constructor.
 101       *
 102       * @since 3.2.0
 103       * @since 4.2.0 Introduced support for naming query clauses by associative array keys.
 104       * @since 5.1.0 Introduced `$compare_key` clause parameter, which enables LIKE key matches.
 105       * @since 5.3.0 Increased the number of operators available to `$compare_key`. Introduced `$type_key`,
 106       *              which enables the `$key` to be cast to a new data type for comparisons.
 107       *
 108       * @param array $meta_query {
 109       *     Array of meta query clauses. When first-order clauses or sub-clauses use strings as
 110       *     their array keys, they may be referenced in the 'orderby' parameter of the parent query.
 111       *
 112       *     @type string $relation Optional. The MySQL keyword used to join the clauses of the query.
 113       *                            Accepts 'AND' or 'OR'. Default 'AND'.
 114       *     @type array  ...$0 {
 115       *         Optional. An array of first-order clause parameters, or another fully-formed meta query.
 116       *
 117       *         @type string|string[] $key         Meta key or keys to filter by.
 118       *         @type string          $compare_key MySQL operator used for comparing the $key. Accepts:
 119       *                                            - '='
 120       *                                            - '!='
 121       *                                            - 'LIKE'
 122       *                                            - 'NOT LIKE'
 123       *                                            - 'IN'
 124       *                                            - 'NOT IN'
 125       *                                            - 'REGEXP'
 126       *                                            - 'NOT REGEXP'
 127       *                                            - 'RLIKE'
 128       *                                            - 'EXISTS' (alias of '=')
 129       *                                            - 'NOT EXISTS' (alias of '!=')
 130       *                                            Default is 'IN' when `$key` is an array, '=' otherwise.
 131       *         @type string          $type_key    MySQL data type that the meta_key column will be CAST to for
 132       *                                            comparisons. Accepts 'BINARY' for case-sensitive regular expression
 133       *                                            comparisons. Default is ''.
 134       *         @type string|string[] $value       Meta value or values to filter by.
 135       *         @type string          $compare     MySQL operator used for comparing the $value. Accepts:
 136       *                                            - '='
 137       *                                            - '!='
 138       *                                            - '>'
 139       *                                            - '>='
 140       *                                            - '<'
 141       *                                            - '<='
 142       *                                            - 'LIKE'
 143       *                                            - 'NOT LIKE'
 144       *                                            - 'IN'
 145       *                                            - 'NOT IN'
 146       *                                            - 'BETWEEN'
 147       *                                            - 'NOT BETWEEN'
 148       *                                            - 'REGEXP'
 149       *                                            - 'NOT REGEXP'
 150       *                                            - 'RLIKE'
 151       *                                            - 'EXISTS'
 152       *                                            - 'NOT EXISTS'
 153       *                                            Default is 'IN' when `$value` is an array, '=' otherwise.
 154       *         @type string          $type        MySQL data type that the meta_value column will be CAST to for
 155       *                                            comparisons. Accepts:
 156       *                                            - 'NUMERIC'
 157       *                                            - 'BINARY'
 158       *                                            - 'CHAR'
 159       *                                            - 'DATE'
 160       *                                            - 'DATETIME'
 161       *                                            - 'DECIMAL'
 162       *                                            - 'SIGNED'
 163       *                                            - 'TIME'
 164       *                                            - 'UNSIGNED'
 165       *                                            Default is 'CHAR'.
 166       *     }
 167       * }
 168       */
 169  	public function __construct( $meta_query = array() ) {
 170          if ( ! $meta_query ) {
 171              return;
 172          }
 173  
 174          if ( isset( $meta_query['relation'] ) ) {
 175              $this->relation = $this->sanitize_relation( $meta_query['relation'] );
 176          } else {
 177              $this->relation = 'AND';
 178          }
 179  
 180          $this->queries = $this->sanitize_query( $meta_query );
 181      }
 182  
 183      /**
 184       * Ensures the 'meta_query' argument passed to the class constructor is well-formed.
 185       *
 186       * Eliminates empty items and ensures that a 'relation' is set.
 187       *
 188       * @since 4.1.0
 189       *
 190       * @param array $queries Array of query clauses.
 191       * @return array Sanitized array of query clauses.
 192       */
 193  	public function sanitize_query( $queries ) {
 194          $clean_queries = array();
 195  
 196          if ( ! is_array( $queries ) ) {
 197              return $clean_queries;
 198          }
 199  
 200          foreach ( $queries as $key => $query ) {
 201              if ( 'relation' === $key ) {
 202                  $relation = $query;
 203  
 204              } elseif ( ! is_array( $query ) ) {
 205                  continue;
 206  
 207                  // First-order clause.
 208              } elseif ( $this->is_first_order_clause( $query ) ) {
 209                  if ( isset( $query['value'] ) && array() === $query['value'] ) {
 210                      unset( $query['value'] );
 211                  }
 212  
 213                  /*
 214                   * Dropping an empty value can leave a clause that is no longer
 215                   * first-order, so sanitize it as a nested query instead. Otherwise
 216                   * it would be stored unsanitized and later treated as a nested
 217                   * query when the SQL is generated.
 218                   */
 219                  if ( ! $this->is_first_order_clause( $query ) ) {
 220                      $query = $this->sanitize_query( $query );
 221                  } elseif ( array_key_exists( 'relation', $query ) ) {
 222                      // A first-order clause has no relation of its own, but never store an unvalidated one.
 223                      $query['relation'] = $this->sanitize_relation( $query['relation'] );
 224                  }
 225  
 226                  $clean_queries[ $key ] = $query;
 227  
 228                  // Otherwise, it's a nested query, so we recurse.
 229              } else {
 230                  $cleaned_query = $this->sanitize_query( $query );
 231  
 232                  if ( ! empty( $cleaned_query ) ) {
 233                      $clean_queries[ $key ] = $cleaned_query;
 234                  }
 235              }
 236          }
 237  
 238          if ( empty( $clean_queries ) ) {
 239              return $clean_queries;
 240          }
 241  
 242          // Sanitize the 'relation' key provided in the query.
 243          if ( isset( $relation ) && 'OR' === $this->sanitize_relation( $relation ) ) {
 244              $clean_queries['relation'] = 'OR';
 245              $this->has_or_relation     = true;
 246  
 247              /*
 248              * If there is only a single clause, call the relation 'OR'.
 249              * This value will not actually be used to join clauses, but it
 250              * simplifies the logic around combining key-only queries.
 251              */
 252          } elseif ( 1 === count( $clean_queries ) ) {
 253              $clean_queries['relation'] = 'OR';
 254  
 255              // Default to AND.
 256          } else {
 257              $clean_queries['relation'] = 'AND';
 258          }
 259  
 260          return $clean_queries;
 261      }
 262  
 263      /**
 264       * Sanitizes a 'relation' operator.
 265       *
 266       * @since 7.1.5
 267       *
 268       * @param mixed $relation Raw relation key from the query argument. Typically the string 'AND' or 'OR'.
 269       * @return string Sanitized relation. Either 'AND' or 'OR'.
 270       * @phpstan-return 'AND'|'OR'
 271       */
 272  	public function sanitize_relation( $relation ) {
 273          if ( is_string( $relation ) && 'OR' === strtoupper( $relation ) ) {
 274              return 'OR';
 275          } else {
 276              return 'AND';
 277          }
 278      }
 279  
 280      /**
 281       * Determines whether a query clause is first-order.
 282       *
 283       * A first-order meta query clause is one that has either a 'key' or
 284       * a 'value' array key.
 285       *
 286       * @since 4.1.0
 287       *
 288       * @param array $query Meta query arguments.
 289       * @return bool Whether the query clause is a first-order clause.
 290       */
 291  	protected function is_first_order_clause( $query ) {
 292          return isset( $query['key'] ) || isset( $query['value'] );
 293      }
 294  
 295      /**
 296       * Constructs a meta query based on 'meta_*' query vars
 297       *
 298       * @since 3.2.0
 299       *
 300       * @param array $qv The query variables.
 301       */
 302  	public function parse_query_vars( $qv ) {
 303          $meta_query = array();
 304  
 305          /*
 306           * For orderby=meta_value to work correctly, simple query needs to be
 307           * first (so that its table join is against an unaliased meta table) and
 308           * needs to be its own clause (so it doesn't interfere with the logic of
 309           * the rest of the meta_query).
 310           */
 311          $primary_meta_query = array();
 312          foreach ( array( 'key', 'compare', 'type', 'compare_key', 'type_key' ) as $key ) {
 313              if ( ! empty( $qv[ "meta_$key" ] ) ) {
 314                  $primary_meta_query[ $key ] = $qv[ "meta_$key" ];
 315              }
 316          }
 317  
 318          // WP_Query sets 'meta_value' = '' by default.
 319          if ( isset( $qv['meta_value'] ) && '' !== $qv['meta_value'] && ( ! is_array( $qv['meta_value'] ) || $qv['meta_value'] ) ) {
 320              $primary_meta_query['value'] = $qv['meta_value'];
 321          }
 322  
 323          $existing_meta_query = isset( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ? $qv['meta_query'] : array();
 324  
 325          if ( ! empty( $primary_meta_query ) && ! empty( $existing_meta_query ) ) {
 326              $meta_query = array(
 327                  'relation' => 'AND',
 328                  $primary_meta_query,
 329                  $existing_meta_query,
 330              );
 331          } elseif ( ! empty( $primary_meta_query ) ) {
 332              $meta_query = array(
 333                  $primary_meta_query,
 334              );
 335          } elseif ( ! empty( $existing_meta_query ) ) {
 336              $meta_query = $existing_meta_query;
 337          }
 338  
 339          $this->__construct( $meta_query );
 340      }
 341  
 342      /**
 343       * Returns the appropriate alias for the given meta type if applicable.
 344       *
 345       * @since 3.7.0
 346       *
 347       * @param string $type MySQL type to cast meta_value.
 348       * @return string MySQL type.
 349       */
 350  	public function get_cast_for_type( $type = '' ) {
 351          if ( empty( $type ) ) {
 352              return 'CHAR';
 353          }
 354  
 355          $meta_type = strtoupper( $type );
 356  
 357          if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) ) {
 358              return 'CHAR';
 359          }
 360  
 361          if ( 'NUMERIC' === $meta_type ) {
 362              $meta_type = 'SIGNED';
 363          }
 364  
 365          return $meta_type;
 366      }
 367  
 368      /**
 369       * Generates SQL clauses to be appended to a main query.
 370       *
 371       * @since 3.2.0
 372       *
 373       * @param string $type              Type of meta. Possible values include but are not limited
 374       *                                  to 'post', 'comment', 'blog', 'term', and 'user'.
 375       * @param string $primary_table     Database table where the object being filtered is stored (eg wp_users).
 376       * @param string $primary_id_column ID column for the filtered object in $primary_table.
 377       * @param object $context           Optional. The main query object that corresponds to the type, for
 378       *                                  example a `WP_Query`, `WP_User_Query`, or `WP_Site_Query`.
 379       *                                  Default null.
 380       * @return string[]|false {
 381       *     Array containing JOIN and WHERE SQL clauses to append to the main query,
 382       *     or false if no table exists for the requested meta type.
 383       *
 384       *     @type string $join  SQL fragment to append to the main JOIN clause.
 385       *     @type string $where SQL fragment to append to the main WHERE clause.
 386       * }
 387       */
 388  	public function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
 389          $meta_table = _get_meta_table( $type );
 390          if ( ! $meta_table ) {
 391              return false;
 392          }
 393  
 394          $this->table_aliases = array();
 395  
 396          $this->meta_table     = $meta_table;
 397          $this->meta_id_column = sanitize_key( $type . '_id' );
 398  
 399          $this->primary_table     = $primary_table;
 400          $this->primary_id_column = $primary_id_column;
 401  
 402          $sql = $this->get_sql_clauses();
 403  
 404          /*
 405           * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should
 406           * be LEFT. Otherwise posts with no metadata will be excluded from results.
 407           */
 408          if ( str_contains( $sql['join'], 'LEFT JOIN' ) ) {
 409              $sql['join'] = str_replace( 'INNER JOIN', 'LEFT JOIN', $sql['join'] );
 410          }
 411  
 412          /**
 413           * Filters the meta query's generated SQL.
 414           *
 415           * @since 3.1.0
 416           *
 417           * @param string[] $sql               Array containing the query's JOIN and WHERE clauses.
 418           * @param array    $queries           Array of meta queries.
 419           * @param string   $type              Type of meta. Possible values include but are not limited
 420           *                                    to 'post', 'comment', 'blog', 'term', and 'user'.
 421           * @param string   $primary_table     Primary table.
 422           * @param string   $primary_id_column Primary column ID.
 423           * @param object   $context           The main query object that corresponds to the type, for
 424           *                                    example a `WP_Query`, `WP_User_Query`, or `WP_Site_Query`.
 425           */
 426          return apply_filters_ref_array( 'get_meta_sql', array( $sql, $this->queries, $type, $primary_table, $primary_id_column, $context ) );
 427      }
 428  
 429      /**
 430       * Generates SQL clauses to be appended to a main query.
 431       *
 432       * Called by the public WP_Meta_Query::get_sql(), this method is abstracted
 433       * out to maintain parity with the other Query classes.
 434       *
 435       * @since 4.1.0
 436       *
 437       * @return string[] {
 438       *     Array containing JOIN and WHERE SQL clauses to append to the main query.
 439       *
 440       *     @type string $join  SQL fragment to append to the main JOIN clause.
 441       *     @type string $where SQL fragment to append to the main WHERE clause.
 442       * }
 443       */
 444  	protected function get_sql_clauses() {
 445          /*
 446           * $queries are passed by reference to get_sql_for_query() for recursion.
 447           * To keep $this->queries unaltered, pass a copy.
 448           */
 449          $queries = $this->queries;
 450          $sql     = $this->get_sql_for_query( $queries );
 451  
 452          if ( ! empty( $sql['where'] ) ) {
 453              $sql['where'] = ' AND ' . $sql['where'];
 454          }
 455  
 456          return $sql;
 457      }
 458  
 459      /**
 460       * Generates SQL clauses for a single query array.
 461       *
 462       * If nested subqueries are found, this method recurses the tree to
 463       * produce the properly nested SQL.
 464       *
 465       * @since 4.1.0
 466       *
 467       * @param array $query Query to parse (passed by reference).
 468       * @param int   $depth Optional. Number of tree levels deep we currently are.
 469       *                     Used to calculate indentation. Default 0.
 470       * @return string[] {
 471       *     Array containing JOIN and WHERE SQL clauses to append to a single query array.
 472       *
 473       *     @type string $join  SQL fragment to append to the main JOIN clause.
 474       *     @type string $where SQL fragment to append to the main WHERE clause.
 475       * }
 476       */
 477  	protected function get_sql_for_query( &$query, $depth = 0 ) {
 478          $sql_chunks = array(
 479              'join'  => array(),
 480              'where' => array(),
 481          );
 482  
 483          $sql = array(
 484              'join'  => '',
 485              'where' => '',
 486          );
 487  
 488          $indent = '';
 489          for ( $i = 0; $i < $depth; $i++ ) {
 490              $indent .= '  ';
 491          }
 492  
 493          foreach ( $query as $key => &$clause ) {
 494              if ( 'relation' === $key ) {
 495                  // Clauses that bypassed sanitize_query() may carry an unvalidated relation.
 496                  $relation = $this->sanitize_relation( $query['relation'] );
 497              } elseif ( is_array( $clause ) ) {
 498  
 499                  // This is a first-order clause.
 500                  if ( $this->is_first_order_clause( $clause ) ) {
 501                      $clause_sql = $this->get_sql_for_clause( $clause, $query, $key );
 502  
 503                      $where_count = count( $clause_sql['where'] );
 504                      if ( ! $where_count ) {
 505                          $sql_chunks['where'][] = '';
 506                      } elseif ( 1 === $where_count ) {
 507                          $sql_chunks['where'][] = $clause_sql['where'][0];
 508                      } else {
 509                          $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
 510                      }
 511  
 512                      $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
 513                      // This is a subquery, so we recurse.
 514                  } else {
 515                      $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
 516  
 517                      $sql_chunks['where'][] = $clause_sql['where'];
 518                      $sql_chunks['join'][]  = $clause_sql['join'];
 519                  }
 520              }
 521          }
 522  
 523          // Filter to remove empties.
 524          $sql_chunks['join']  = array_filter( $sql_chunks['join'] );
 525          $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
 526  
 527          if ( empty( $relation ) ) {
 528              $relation = 'AND';
 529          }
 530  
 531          // Filter duplicate JOIN clauses and combine into a single string.
 532          if ( ! empty( $sql_chunks['join'] ) ) {
 533              $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
 534          }
 535  
 536          // Generate a single WHERE clause with proper brackets and indentation.
 537          if ( ! empty( $sql_chunks['where'] ) ) {
 538              $sql['where'] = '( ' . "\n  " . $indent . implode( ' ' . "\n  " . $indent . $relation . ' ' . "\n  " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
 539          }
 540  
 541          return $sql;
 542      }
 543  
 544      /**
 545       * Generates SQL JOIN and WHERE clauses for a first-order query clause.
 546       *
 547       * "First-order" means that it's an array with a 'key' or 'value'.
 548       *
 549       * @since 4.1.0
 550       *
 551       * @global wpdb $wpdb WordPress database abstraction object.
 552       *
 553       * @param array  $clause       Query clause (passed by reference).
 554       * @param array  $parent_query Parent query array.
 555       * @param string $clause_key   Optional. The array key used to name the clause in the original `$meta_query`
 556       *                             parameters. If not provided, a key will be generated automatically.
 557       *                             Default empty string.
 558       * @return array {
 559       *     Array containing JOIN and WHERE SQL clauses to append to a first-order query.
 560       *
 561       *     @type string[] $join  Array of SQL fragments to append to the main JOIN clause.
 562       *     @type string[] $where Array of SQL fragments to append to the main WHERE clause.
 563       * }
 564       */
 565  	public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) {
 566          global $wpdb;
 567  
 568          $sql_chunks = array(
 569              'where' => array(),
 570              'join'  => array(),
 571          );
 572  
 573          if ( isset( $clause['compare'] ) ) {
 574              $clause['compare'] = strtoupper( $clause['compare'] );
 575          } else {
 576              $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
 577          }
 578  
 579          $non_numeric_operators = array(
 580              '=',
 581              '!=',
 582              'LIKE',
 583              'NOT LIKE',
 584              'IN',
 585              'NOT IN',
 586              'EXISTS',
 587              'NOT EXISTS',
 588              'RLIKE',
 589              'REGEXP',
 590              'NOT REGEXP',
 591          );
 592  
 593          $numeric_operators = array(
 594              '>',
 595              '>=',
 596              '<',
 597              '<=',
 598              'BETWEEN',
 599              'NOT BETWEEN',
 600          );
 601  
 602          if ( ! in_array( $clause['compare'], $non_numeric_operators, true ) && ! in_array( $clause['compare'], $numeric_operators, true ) ) {
 603              $clause['compare'] = '=';
 604          }
 605  
 606          if ( isset( $clause['compare_key'] ) ) {
 607              $clause['compare_key'] = strtoupper( $clause['compare_key'] );
 608          } else {
 609              $clause['compare_key'] = isset( $clause['key'] ) && is_array( $clause['key'] ) ? 'IN' : '=';
 610          }
 611  
 612          if ( ! in_array( $clause['compare_key'], $non_numeric_operators, true ) ) {
 613              $clause['compare_key'] = '=';
 614          }
 615  
 616          $meta_compare     = $clause['compare'];
 617          $meta_compare_key = $clause['compare_key'];
 618  
 619          // First build the JOIN clause, if one is required.
 620          $join = '';
 621  
 622          // We prefer to avoid joins if possible. Look for an existing join compatible with this clause.
 623          $alias = $this->find_compatible_table_alias( $clause, $parent_query );
 624          if ( false === $alias ) {
 625              $i     = count( $this->table_aliases );
 626              $alias = $i ? 'mt' . $i : $this->meta_table;
 627  
 628              // JOIN clauses for NOT EXISTS have their own syntax.
 629              if ( 'NOT EXISTS' === $meta_compare ) {
 630                  $join .= " LEFT JOIN $this->meta_table";
 631                  $join .= $i ? " AS $alias" : '';
 632  
 633                  if ( 'LIKE' === $meta_compare_key ) {
 634                      $join .= $wpdb->prepare( " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key LIKE %s )", '%' . $wpdb->esc_like( $clause['key'] ) . '%' );
 635                  } else {
 636                      $join .= $wpdb->prepare( " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
 637                  }
 638  
 639                  // All other JOIN clauses.
 640              } else {
 641                  $join .= " INNER JOIN $this->meta_table";
 642                  $join .= $i ? " AS $alias" : '';
 643                  $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )";
 644              }
 645  
 646              $this->table_aliases[] = $alias;
 647              $sql_chunks['join'][]  = $join;
 648          }
 649  
 650          // Save the alias to this clause, for future siblings to find.
 651          $clause['alias'] = $alias;
 652  
 653          // Determine the data type.
 654          $_meta_type     = $clause['type'] ?? '';
 655          $meta_type      = $this->get_cast_for_type( $_meta_type );
 656          $clause['cast'] = $meta_type;
 657  
 658          // Fallback for clause keys is the table alias. Key must be a string.
 659          if ( is_int( $clause_key ) || ! $clause_key ) {
 660              $clause_key = $clause['alias'];
 661          }
 662  
 663          // Ensure unique clause keys, so none are overwritten.
 664          $iterator        = 1;
 665          $clause_key_base = $clause_key;
 666          while ( isset( $this->clauses[ $clause_key ] ) ) {
 667              $clause_key = $clause_key_base . '-' . $iterator;
 668              ++$iterator;
 669          }
 670  
 671          // Store the clause in our flat array.
 672          $this->clauses[ $clause_key ] =& $clause;
 673  
 674          // Next, build the WHERE clause.
 675  
 676          // meta_key.
 677          if ( array_key_exists( 'key', $clause ) ) {
 678              if ( 'NOT EXISTS' === $meta_compare ) {
 679                  $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
 680              } else {
 681                  /**
 682                   * In joined clauses negative operators have to be nested into a
 683                   * NOT EXISTS clause and flipped, to avoid returning records with
 684                   * matching post IDs but different meta keys. Here we prepare the
 685                   * nested clause.
 686                   */
 687                  if ( in_array( $meta_compare_key, array( '!=', 'NOT IN', 'NOT LIKE', 'NOT EXISTS', 'NOT REGEXP' ), true ) ) {
 688                      // Negative clauses may be reused.
 689                      $i                     = count( $this->table_aliases );
 690                      $subquery_alias        = $i ? 'mt' . $i : $this->meta_table;
 691                      $this->table_aliases[] = $subquery_alias;
 692  
 693                      $meta_compare_string_start  = 'NOT EXISTS (';
 694                      $meta_compare_string_start .= "SELECT 1 FROM $wpdb->postmeta $subquery_alias ";
 695                      $meta_compare_string_start .= "WHERE $subquery_alias.post_ID = $alias.post_ID ";
 696                      $meta_compare_string_end    = 'LIMIT 1';
 697                      $meta_compare_string_end   .= ')';
 698                  }
 699  
 700                  switch ( $meta_compare_key ) {
 701                      case '=':
 702                      case 'EXISTS':
 703                          $where = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
 704                          break;
 705                      case 'LIKE':
 706                          $meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%';
 707                          $where              = $wpdb->prepare( "$alias.meta_key LIKE %s", $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
 708                          break;
 709                      case 'IN':
 710                          $meta_compare_string = "$alias.meta_key IN (" . substr( str_repeat( ',%s', count( $clause['key'] ) ), 1 ) . ')';
 711                          $where               = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
 712                          break;
 713                      case 'RLIKE':
 714                      case 'REGEXP':
 715                          $operator = $meta_compare_key;
 716                          if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) {
 717                              $cast     = 'BINARY';
 718                              $meta_key = "CAST($alias.meta_key AS BINARY)";
 719                          } else {
 720                              $cast     = '';
 721                              $meta_key = "$alias.meta_key";
 722                          }
 723                          $where = $wpdb->prepare( "$meta_key $operator $cast %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
 724                          break;
 725  
 726                      case '!=':
 727                      case 'NOT EXISTS':
 728                          $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key = %s " . $meta_compare_string_end;
 729                          $where               = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
 730                          break;
 731                      case 'NOT LIKE':
 732                          $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key LIKE %s " . $meta_compare_string_end;
 733  
 734                          $meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%';
 735                          $where              = $wpdb->prepare( $meta_compare_string, $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
 736                          break;
 737                      case 'NOT IN':
 738                          $array_subclause     = '(' . substr( str_repeat( ',%s', count( $clause['key'] ) ), 1 ) . ') ';
 739                          $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key IN " . $array_subclause . $meta_compare_string_end;
 740                          $where               = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
 741                          break;
 742                      case 'NOT REGEXP':
 743                          $operator = $meta_compare_key;
 744                          if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) {
 745                              $cast     = 'BINARY';
 746                              $meta_key = "CAST($subquery_alias.meta_key AS BINARY)";
 747                          } else {
 748                              $cast     = '';
 749                              $meta_key = "$subquery_alias.meta_key";
 750                          }
 751  
 752                          $meta_compare_string = $meta_compare_string_start . "AND $meta_key REGEXP $cast %s " . $meta_compare_string_end;
 753                          $where               = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
 754                          break;
 755                  }
 756  
 757                  $sql_chunks['where'][] = $where;
 758              }
 759          }
 760  
 761          // meta_value.
 762          if ( array_key_exists( 'value', $clause ) ) {
 763              $meta_value = $clause['value'];
 764  
 765              if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) {
 766                  if ( ! is_array( $meta_value ) ) {
 767                      $meta_value = preg_split( '/[,\s]+/', $meta_value );
 768                  }
 769              } elseif ( is_string( $meta_value ) ) {
 770                  $meta_value = trim( $meta_value );
 771              }
 772  
 773              switch ( $meta_compare ) {
 774                  case 'IN':
 775                  case 'NOT IN':
 776                      $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
 777                      $where               = $wpdb->prepare( $meta_compare_string, $meta_value );
 778                      break;
 779  
 780                  case 'BETWEEN':
 781                  case 'NOT BETWEEN':
 782                      $where = $wpdb->prepare( '%s AND %s', $meta_value[0], $meta_value[1] );
 783                      break;
 784  
 785                  case 'LIKE':
 786                  case 'NOT LIKE':
 787                      $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
 788                      $where      = $wpdb->prepare( '%s', $meta_value );
 789                      break;
 790  
 791                  // EXISTS with a value is interpreted as '='.
 792                  case 'EXISTS':
 793                      $meta_compare = '=';
 794                      $where        = $wpdb->prepare( '%s', $meta_value );
 795                      break;
 796  
 797                  // 'value' is ignored for NOT EXISTS.
 798                  case 'NOT EXISTS':
 799                      $where = '';
 800                      break;
 801  
 802                  default:
 803                      $where = $wpdb->prepare( '%s', $meta_value );
 804                      break;
 805  
 806              }
 807  
 808              if ( $where ) {
 809                  if ( 'CHAR' === $meta_type ) {
 810                      $sql_chunks['where'][] = "$alias.meta_value {$meta_compare} {$where}";
 811                  } else {
 812                      $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}";
 813                  }
 814              }
 815          }
 816  
 817          /*
 818           * Multiple WHERE clauses (for meta_key and meta_value) should
 819           * be joined in parentheses.
 820           */
 821          if ( 1 < count( $sql_chunks['where'] ) ) {
 822              $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
 823          }
 824  
 825          return $sql_chunks;
 826      }
 827  
 828      /**
 829       * Gets a flattened list of sanitized meta clauses.
 830       *
 831       * This array should be used for clause lookup, as when the table alias and CAST type must be determined for
 832       * a value of 'orderby' corresponding to a meta clause.
 833       *
 834       * @since 4.2.0
 835       *
 836       * @return array Meta clauses.
 837       */
 838  	public function get_clauses() {
 839          return $this->clauses;
 840      }
 841  
 842      /**
 843       * Identifies an existing table alias that is compatible with the current
 844       * query clause.
 845       *
 846       * We avoid unnecessary table joins by allowing each clause to look for
 847       * an existing table alias that is compatible with the query that it
 848       * needs to perform.
 849       *
 850       * An existing alias is compatible if (a) it is a sibling of `$clause`
 851       * (ie, it's under the scope of the same relation), and (b) the combination
 852       * of operator and relation between the clauses allows for a shared table join.
 853       * In the case of WP_Meta_Query, this only applies to 'IN' clauses that are
 854       * connected by the relation 'OR'.
 855       *
 856       * @since 4.1.0
 857       *
 858       * @param array $clause       Query clause.
 859       * @param array $parent_query Parent query of $clause.
 860       * @return string|false Table alias if found, otherwise false.
 861       */
 862  	protected function find_compatible_table_alias( $clause, $parent_query ) {
 863          $alias = false;
 864  
 865          foreach ( $parent_query as $sibling ) {
 866              // If the sibling has no alias yet, there's nothing to check.
 867              if ( empty( $sibling['alias'] ) ) {
 868                  continue;
 869              }
 870  
 871              // We're only interested in siblings that are first-order clauses.
 872              if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
 873                  continue;
 874              }
 875  
 876              $compatible_compares = array();
 877  
 878              // Clauses connected by OR can share joins as long as they have "positive" operators.
 879              if ( 'OR' === $parent_query['relation'] ) {
 880                  $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
 881  
 882                  // Clauses joined by AND with "negative" operators share a join only if they also share a key.
 883              } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
 884                  $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' );
 885              }
 886  
 887              $clause_compare  = strtoupper( $clause['compare'] );
 888              $sibling_compare = strtoupper( $sibling['compare'] );
 889              if ( in_array( $clause_compare, $compatible_compares, true ) && in_array( $sibling_compare, $compatible_compares, true ) ) {
 890                  $alias = preg_replace( '/\W/', '_', $sibling['alias'] );
 891                  break;
 892              }
 893          }
 894  
 895          /**
 896           * Filters the table alias identified as compatible with the current clause.
 897           *
 898           * @since 4.1.0
 899           *
 900           * @param string|false  $alias        Table alias, or false if none was found.
 901           * @param array         $clause       First-order query clause.
 902           * @param array         $parent_query Parent of $clause.
 903           * @param WP_Meta_Query $query        WP_Meta_Query object.
 904           */
 905          return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this );
 906      }
 907  
 908      /**
 909       * Checks whether the current query has any OR relations.
 910       *
 911       * In some cases, the presence of an OR relation somewhere in the query will require
 912       * the use of a `DISTINCT` or `GROUP BY` keyword in the `SELECT` clause. The current
 913       * method can be used in these cases to determine whether such a clause is necessary.
 914       *
 915       * @since 4.3.0
 916       *
 917       * @return bool True if the query contains any `OR` relations, otherwise false.
 918       */
 919  	public function has_or_relation() {
 920          return $this->has_or_relation;
 921      }
 922  }


Generated : Thu Nov 19 08:20:01 2026 Cross-referenced by PHPXref