Multiple Values stored as array in Meta Query

I’m a little confused as to best practise for saving multi-select values in meta fields.

Assuming

Read More
<select multiple name="_casestudypost[]">

is my form field

if I store $_POST[‘_casestudypost’] in a meta_key of the same name? (which returns an array) – how can I find out when 281 is in that array. I’ve tried:

$args = array(
            'meta_query'=> array(
                array(
                    'key'=>'_casestudypost',
                    'value'=>  281,
                    'compare' => 'IN',
                    'type' => 'NUMERIC'
                )
            ),
            'post_type'=>'case_studies',
            'post_status' => 'publish'
        );

However the generated SQL that WordPress generates under the hood seems to ask, is meta_value (13,281,45) in 281, rather than is 281 in meta_value (13,281,45).

Related posts

Leave a Reply

2 comments

  1. An IN query is not a string comparison query. It is more like a bunch of OR statements.

    ... WHERE tablename.animal IN ('cat','dog','ferret')
    

    is going to be the same as

    ...WHERE tablename.animal = 'cat'
          OR tablename.animal = 'dog'
          OR tablename.animal = 'ferret'
    

    $_POST['_casestudypost'] is going to be an array, and if you stored it as a single value in postmeta it is going to be serialized. The array array("animal" => "cat"); when serialized will look something like a:1:{s:6:"animal";s:3:"cat";}. Your actual $_POST['_casestudypost'] value will be similarly transformed. That is very far from what you need.

    If you are going to be pulling by values, or key/value pairs, store each of your selected $_POST['_casestudypost'] values individually in the database– each value with its own line and not as a single key/value pair holding a serialized array.

    If you don’t have to search by the value, then save the serialized array.

    There is not enough context to your question for me to tell whether you really need to be searching by the value or not. There may be ways to get the result you want that you aren’t thinking about.

  2. The default compare value in a meta_query is =, which is what you want. Assuming I understand your question correctly, the following is what you want.

    $args = array(
                'meta_query'=> array(
                    array(
                        'key'=>'_casestudypost',
                        'value'=>  281,
                        'type' => 'NUMERIC'
                    )
                ),
                'post_type'=>'case_studies',
                'post_status' => 'publish'
            );
    

    compare (string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or '<='. Default value is '='. (paraphrased to address meta_query)