I’m a little confused as to best practise for saving multi-select values in meta fields.
Assuming
<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).
An
IN
query is not a string comparison query. It is more like a bunch ofOR
statements.is going to be the same as
$_POST['_casestudypost']
is going to be an array, and if you stored it as a single value in postmeta it is going to beserialize
d. The arrayarray("animal" => "cat");
when serialized will look something likea: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.
The default
compare
value in ameta_query
is=
, which is what you want. Assuming I understand your question correctly, the following is what you want.compare (string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or '<='. Default value is '='.
(paraphrased to address meta_query)