So, I have a search form, that returns custom posts with wp_query
. Now I need to find posts with a custom field and specific value: Lets say I have multiple checkboxes named catagories[]
. So when I save them it makes a serialized array in db. Now I need to search in the front end posts with lets say value 11 in it. Array looks like that: a:3:{i:1;s:2:"11";i:2;s:2:"33";i:3;s:2:"33";}
. So here comes the problem, how can I retrieve information from this serialized array to find all posts with value 11. My code is:
$args = array(
'post_type'=>'paibcresume',
'posts_per_page' => 10,
'paged' => $paged,
'meta_query' => array(),
'tax_query' => array(),
'orderby' => 'date',
'meta_key' => '',
'order' => 'DESC'
);
// BASIC SEARCH FORM
// Search by category
// rbsercategories
// rbwwcategoryhidden
if (isset($_GET['rbsercategories']) && !empty($_GET['rbsercategories'])) {
$args['meta_query'][] = array(
'key' => 'rbwwcategoryhidden',
'value' => $_GET['rbsercategories'],
'compare' => 'IN'
);
}
$the_query = new WP_Query( $args );
while ($the_query->have_posts() ) : $the_query->the_post();
This code works if values in data base are not a serialized array, just simple strings, but doesn’t work with arrays so what do I have to do?
Ok, I didn’t find the way to search thru serialized arrays, but I found the way to work around it.
So I didn’t change any fields in admin, instead I added new with a loop. So I have this fields named
rbwwcategoryhidden[]
, that create this array. I unserialized that array and created new fields for each value:So now I got new fields, I personaly have a limit of three fields (user can only check three checkboxes):
rbwwcatforsearch1, rbwwcatforsearch2, rbwwcatforsearch3
. And I added value to each field from that array: 11, 33 and 33.And now I just changed the meta_query code in the front end, and it looks like that:
And it works just perfect 🙂