I find myself facing a situation where I will have a bunch of custom post types and I want to select those with specific meta values. There is a slight wrinkle in that the value I want to select against is within a larger array stored to a single meta key.
I'm pretty sure I could write an SQL select statement using LIKE "%$myterm:$myvalue%"
but I wondered if there was an easier way?
I find myself facing a situation where I will have a bunch of custom post types and I want to select those with specific meta values. There is a slight wrinkle in that the value I want to select against is within a larger array stored to a single meta key.
I'm pretty sure I could write an SQL select statement using LIKE "%$myterm:$myvalue%"
but I wondered if there was an easier way?
1 Answer
Reset to default 1I think I am understanding your correctly...If I'm way off, let me know!
// Assuming ideas is an array and you are looking for ideas=>two
$query = new WP_Query(
array(
// You can pass 'any' to post_type, but you get a hold of revisions, attachments, and menu_items. But I am not sure how many Custom Post Types you have ¯\_(ツ)_/¯
'post_type' => array('cpt_one', 'cpt_two', 'cpt_three', 'etc'),
'meta_query' => array(
array(
'key' => 'ideas',
'value' => array('one', 'two', 'three'),
'compare' => 'IN'
)
)
)
);
// ideas is still an array here, and the value of 'two' lives inside of that ideas array()
$query = new WP_Query(
array(
'post_type' => array('cpt_one', 'cpt_two', 'cpt_three', 'etc'),
'meta_query' => array(
array(
'key' => 'ideas',
'value' => 'two',
'compare' => 'LIKE' // Less-known and not explained well in the docs.
)
)
)
);
Going back to Jacob Peattie's point, querying can be heavy at times depending on the complexity of your arrays. Again, if I am off here....let me know!
foo=>bar
butfoo=>(bar=>baz,lar=>nar)
wherefoo
,baz
, andnar
could literally be anything. I'm halfway tempted to rejig it with a custom table - at least as an index of thefoo
vsbaz
. – Matthew Brown aka Lord Matt Commented Jun 12, 2019 at 15:26