From a7c2180672bbf621333af9c2a380c0f06d17c6d9 Mon Sep 17 00:00:00 2001 From: Scott Taylor Date: Wed, 4 Jun 2014 05:48:14 +0000 Subject: [PATCH] Fix SQL generation when `meta_query` has an `'relation' => 'OR'` for its queries and wants to `'orderby' => 'meta_value'`. Adds unit test. Props jackreichert. Fixes #25538. Built from https://develop.svn.wordpress.org/trunk@28659 git-svn-id: http://core.svn.wordpress.org/trunk@28477 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- wp-includes/meta.php | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/wp-includes/meta.php b/wp-includes/meta.php index 1b72ca317a..cb83e4600e 100644 --- a/wp-includes/meta.php +++ b/wp-includes/meta.php @@ -972,6 +972,7 @@ class WP_Meta_Query { $where["key-only-$key"] = $wpdb->prepare( "$meta_table.meta_key = %s", trim( $q['key'] ) ); } + $where_meta_key = array(); foreach ( $queries as $k => $q ) { $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : ''; $meta_type = $this->get_cast_for_type( isset( $q['type'] ) ? $q['type'] : '' ); @@ -1014,12 +1015,18 @@ class WP_Meta_Query { $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)"; $where[$k] = ''; - if ( !empty( $meta_key ) ) - $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key ); + if ( ! empty( $meta_key ) ) { + if ( isset( $q['compare'] ) ) { + $where_meta_key[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key ); + } else { + $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key ); + } + } if ( is_null( $meta_value ) ) { - if ( empty( $where[$k] ) ) + if ( empty( $where[$k] ) && empty( $where_meta_key ) ) { unset( $join[$i] ); + } continue; } @@ -1060,6 +1067,10 @@ class WP_Meta_Query { else $where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )'; + if ( ! empty( $where_meta_key ) ) { + $where .= "\nAND " . implode( "\nAND ", $where_meta_key ); + } + $join = implode( "\n", $join ); if ( ! empty( $join ) ) $join = ' ' . $join;