0

Looking for a method to nest AND/OR relation in meta_query based on array serialized values.

Reviewed these already: Query multiple meta key values? WP Meta Query for some meta (array) values

I understand that the serialized data 'should not' be used to search/filter (or first needs to be pulled out to do so outside the SQL) BUT I would like to put it out there so see if nesting could do the trick.

E.g. Data [ meta_value field1 = 'abc' , meta_value field2 a:2:{i:0;s:1:"1";i:1;s:1:"4";} ]

This holds the values [ "1", "4"] as string array.

The search I would like to perform is something like

$metaSearchQuery = [
            'relation'    => 'AND',
            [
               'key' => '<FIELDNAME1>',
                'value' => 'abc'
            ],
            [
            'relation'    => 'OR',
               [
                  'key'          => '<FIELDNAME2>',
                  'value'        => serialize(strval(1)),
                  'compare'      => 'like',
               ],
               [
                  'key'          => '<FIELDNAME2>',
                  'value'        => serialize(strval(4)),
                  'compare'      => 'like',
               ],
               ...............
            ]
        ];

With the output SQL something like

... where meta_value.field1 = 'abc' and (field2 like 's:1:"1"' or field2 like 's:1:"4"')

That way you could use the main 'AND' condition for other fields and nest 'OR' for array values...? Is this even possible using meta_query?

The reason is that I do have to filter and the values could be 1, 2, 3, 4 or any combination of there. Taxonomy better , yes but this has been written already so would like to utilise the meta structure if possible.

1 Answer 1

0

Probably should have waited a bit but after posting the question I found a solution based on my points above and repeated here:

https://codex.wordpress.org/Class_Reference/WP_Meta_Query

https://generatewp.com/filtering-data-with-wp_meta_query/

My Solution:

$metaSearchSubQuery = [
            'relation' => 'OR'    
        ];

foreach($eventTypeId as $id) {
    $metaSearchSubQuery[] = [
        'key'          => 'EventId',
        'value'        => serialize($id),
        'compare'      => 'like'
    ];
}

$metaSearchQuery[] = $metaSearchSubQuery;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.