Make WordPress Core

Opened 11 years ago

Closed 10 years ago

#24576 closed enhancement (wontfix)

Make WP_Meta_Query accept arrays for keys

Reported by: viper007bond's profile Viper007Bond Owned by:
Milestone: Priority: lowest
Severity: trivial Version: 3.5.1
Component: Query Keywords: needs-patch meta-query needs-unit-tests
Focuses: Cc:

Description

#20312 touches on this but I thought of a much better solution for more complicated logic while still sticking to the API: allow the key to be an array which would inverse the overall relation value:

For example, say you want this:

( key1 = abc OR key2 = abc ) AND key3 = def

You could simply do this:

'meta_query' => array(
	'relation' => 'AND',
	array(
		'key' => array( 'key1', 'key2' ),
		'value' => 'abc',
	),
	array(
		'key' => 'key3',
		'value' => 'def',
	),
),

Or for this:

( key1 = abc AND key2 = abc ) OR key3 = def

You'd just switch the relation to OR.

Certainly edge case but I'm throwing it out there because I hate using filters to hack away at the SQL directly. :)

Change History (4)

#1 @rmccue
11 years ago

+1. Would this allow the value to be an equal sized array for ( key1 = abc OR key2 = def )? (That probably introduces extra complexity, but gives it similar behaviour to str_replace())

#2 @wonderboymusic
11 years ago

  • Keywords meta-query added

#3 @wonderboymusic
11 years ago

  • Keywords needs-unit-tests added
  • Milestone changed from Awaiting Review to Future Release

#4 @boonebgorges
10 years ago

  • Milestone Future Release deleted
  • Resolution set to wontfix
  • Status changed from new to closed

I don't think this is necessary anymore now that you can nest queries [29887]. ( key1 = abc OR key2 = abc ) AND key3 = def becomes:

array(
    'relation' => 'AND',
    array(
        'relation' => 'OR',
        array(
            'key' => 'key1',
            'value' => 'abc',
        ),
        array(
            'key' => 'key2',
            'value' => 'abc',
        ),
    ),
    array(
        'key' => 'key3',
        'value' => 'def',
    ),
)

A little more verbose than what Viper007Bond originally suggested, but it has the virtue of being unambiguous: we don't have to decide whether the array of keys should be interpreted with AND or OR logic.

Note: See TracTickets for help on using tickets.