meta query - meta_query to check all custom fields

admin2025-06-04  11

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',
    array(
        '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?
Thanks

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',
    array(
        '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?
Thanks

Share Improve this question asked Jan 10, 2019 at 10:37 AbhikAbhik 2,9212 gold badges24 silver badges31 bronze badges 1
  • I’m afraid that the only solution is to use custom SQL with LIKE using posts_where and posts_join filters – Krzysiek Dróżdż Commented Jan 10, 2019 at 10:49
Add a comment  | 

1 Answer 1

Reset to default 0

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749025790a315729.html

最新回复(0)