I have to use the meta_query argument so that it checks for a keyword in all available custom field values (in array format) saved for the object. The meta keys are different for every object, therefor I can't use any static key.

This is something I want to achieve.

'meta_query' => array(
    'relation' => 'OR',
        'key' => 'state', // This is where I am lost
        'value' => 'mykeyword', //Keyword to look for
        'compare' => 'EXISTS' //If keword exists in value (array)

Can this be done using meta_query or do I need to use custom database query?

  • I’m afraid that the only solution is to use custom SQL with LIKE using posts_where and posts_join filters – Krzysiek Dróżdż Jan 10 '19 at 10:49

Short of coming up with a MySQL query yourself, you could get a list of distinct meta_keys and build your query array based on the results.

On another note, I think you may have misunderstood the meaning of EXISTS. It doesn't denote finding the value parameter passed within the value of the given meta. I think you actually mean LIKE, but please correct me if I'm wrong.

$query_arg = array(

global $wpdb;

$meta_keys = $wpdb->get_col("SELECT DISTINCT `meta_key` FROM {$wpdb->postmeta}");

foreach($meta_keys as $meta_key){
    $query_arg['meta_query'][] = array(
        'key' => $meta_key,
        'value' => 'mykeyword',
        'compare' => 'LIKE'

$query_arg['relation'] = 'OR';

Although this is likely not the most optimised way of doing things, from a MySQL standpoint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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