From 381583c21fec6b4c2abea4bf13d68027b1c03751 Mon Sep 17 00:00:00 2001 From: Ryan Boren Date: Wed, 3 Oct 2012 12:35:06 +0000 Subject: [PATCH] Improve performance of WP_Meta_Query when doing OR queries on meta keys. Props joehoyle, SergeyBiryukov. fixes #19729 git-svn-id: https://develop.svn.wordpress.org/trunk@22103 602fd350-edb4-49c9-b593-d223f7449a82 --- wp-includes/meta.php | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/wp-includes/meta.php b/wp-includes/meta.php index 39646440f0..d95ce47a22 100644 --- a/wp-includes/meta.php +++ b/wp-includes/meta.php @@ -711,7 +711,30 @@ class WP_Meta_Query { $join = array(); $where = array(); - foreach ( $this->queries as $k => $q ) { + $key_only_queries = array(); + $queries = array(); + + // Split out the meta_key only queries (we can only do this for OR) + if ( 'OR' == $this->relation ) { + foreach ( $this->queries as $k => $q ) { + if ( ! isset( $q['value'] ) && ! empty( $q['key'] ) ) + $key_only_queries[$k] = $q; + else + $queries[$k] = $q; + } + } else { + $queries = $this->queries; + } + + // Specify all the meta_key only queries in one go + if ( $key_only_queries ) { + $join[] = "INNER JOIN $meta_table ON $primary_table.$primary_id_column = $meta_table.$meta_id_column"; + + foreach ( $key_only_queries as $key => $q ) + $where["key-only-$key"] = $wpdb->prepare( "$meta_table.meta_key = %s", trim( $q['key'] ) ); + } + + foreach ( $queries as $k => $q ) { $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : ''; $meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR';