meta query - meta_query with multiple key

admin2025-06-01  2

I have a search input then I want to display all the data searched in multiple meta_key. How can I make it?

This is my code

$filter = array(
    'post_type'     => 'request',
    'post_status'   => 'publish',
    'posts_per_page' => -1,
    'meta_query' => array(
        "relation" => "AND",
        array(
            'key' => array($key1, $key2, $key3),
            'value' => $search_value,
            'compare' => 'LIKE',
        )
    )
);

I have a search input then I want to display all the data searched in multiple meta_key. How can I make it?

This is my code

$filter = array(
    'post_type'     => 'request',
    'post_status'   => 'publish',
    'posts_per_page' => -1,
    'meta_query' => array(
        "relation" => "AND",
        array(
            'key' => array($key1, $key2, $key3),
            'value' => $search_value,
            'compare' => 'LIKE',
        )
    )
);
Share Improve this question asked Nov 29, 2017 at 10:13 user132319user132319 11 silver badge1 bronze badge 1
  • try with "compare" => "IN". look here for other possibilities : codex.wordpress/Class_Reference/… – mmm Commented Nov 29, 2017 at 10:46
Add a comment  | 

1 Answer 1

Reset to default 2

key in a meta query needs to be a string, you can't pass multiple keys to a single meta query. You'll need add a query for each key:

$filter = array(
    'post_type'      => 'request',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => array(
        'relation' => 'OR',
        array(
            'key'     => $key1,
            'value'   => $search_value,
            'compare' => 'LIKE',
        ),
        array(
            'key'     => $key2,
            'value'   => $search_value,
            'compare' => 'LIKE',
        ),
        array(
            'key'     => $key3,
            'value'   => $search_value,
            'compare' => 'LIKE',
        ),
    ),
);

Note that I set 'relation' to 'OR' so that results will be returned for posts that match any of the keys, rather than all. If you need results to have matches for all the keys, change it back to 'AND'.

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

最新回复(0)