WordPress: meta_query and array - php

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:
$wwCategory = get_post_custom_values('rbwwcategoryhidden');
foreach($wwCategory as $wwCategoryValue){$wwCategoryUnser = unserialize($wwCategoryValue);}
$rbWwCatSearchCounter='0';
foreach($wwCategoryUnser as $catId){
$rbWwCatSearchCounter++;
echo '<input type="text" name="rbwwcatforsearch'.$rbWwCatSearchCounter.'" id="rbwwcatforsearch'.$rbWwCatSearchCounter.'" value="'.$catId.'">';
}
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:
// Search by category
if (isset($_GET['rbsercategories']) && !empty($_GET['rbsercategories'])) {
$args['meta_query'][] = array(
'key' => array('rbwwcatforsearch1','rbwwcatforsearch2','rbwwcatforsearch3'),
'value' => (isset($_GET['rbsercategories'])?$_GET['rbsercategories']:array()),
'compare' => 'IN'
);
}
And it works just perfect :)

Related

WordPress - get_posts by meta_query where key CONTAINS certain string

I am trying to run a PHP get_posts query in WordPress to target posts with a meta data key that CONTAINS a certain string. The issue is, I don't know the full key name as it is created independently by another plugin but all keys have in common that they start with "_cegg_data".
Sometimes the field will be called "_cegg_data_ae_googlecom", other times "_cegg_data_ae_youtubecom" and so on.
Is there a way to run a query posts with a meta_query that contains "_cegg_data" in the key (value unknown as well)?
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_cegg_data{{anything here}}'
)
)
);
$postslist = get_posts( $args );
You can add a LIKE comparison for partial string macthing.
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_cegg_data',
'compare' => 'LIKE',
'value' => '_cegg_data%'
)
)
);
$postslist = get_posts($args);
The % will work as a wildcard matching any number of characters, so this will get every product post where the key starts with _cegg_data.

How to do meta_query with ACF checkbox values as they store themselves as arrays?

I have a custom post type "Product", I have created 4 checkbox option for a field "Select Category", User can select multiple option at a time. For Some reason I am not using taxonomy to classify products.
So when I do meta_query, it do not result anything. Basically, I have selected, category for every product in the custom post type "Product", but ACF store it's checkbox value in array, and the meta_query can't search that array as a whole. However it can search from an array. My code is as follows:
$args = array(
'post_type' => 'fproduct',
'meta_query' => array(
array(
'key' => 'select_product_categories',
'value' => array('Indoor Games', 'Property Management'),
'compare' => 'IN',
),
),
);
// query
$wp_query = new WP_Query( $args );
echo "<pre>"; print_r($wp_query); echo "</pre>"; die;
So how can I search so that checkbox can work, also I can not get the checkbox value on a template, as it for post type for different products.
I have solved my problem as the checkbox is stored in searialized array, so instead of 'IN', 'LIKE' will work, so here goes the query -
$args = array(
'post_type' => 'fproduct',
'meta_query' => array(
array(
'key' => 'select_product_categories',
'value' => array('"Indoor Games"', '"Property Management"'),
'compare' => 'LIKE',
),
),
);
In ACF checkbox, what value have you set?
Furthermore, using the IN operator, it does not work in these cases. Just try using the LIKE operator:
"compare" => "LIKE".
However, it is a totally wrong way to create a taxonomy in Wordpress, because in this way, you have to restructure all the queries and the system is much less powerful, because the database tables do not have relations between them.

Use ACF checkbox value array to find "More like this"

I'm using an ACF checkbox to designate categories (called "aims") for Psychology apps/sites. So values would be, say, "Mindfulness", "Well-Being" and "Depression".
Since it's possible to select multiple values, what I'd like to do is have a More Like This where any single post could show other posts that match one or more of the categories of the post.
UPDATE: Here's the code I'm using now, which I'm still not having any luck with:
the_field( 'aims'); /* since I'm on the page for a single post, this gives me the aims for the current post and is currently returning values from the checkbox with multiple selections (as an array, I believe) */
$args = array(
'numberposts' => -1,
'post_type' => 'program',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'aims',
'value' => 'Well-Being', /* I'd actually like this to use the aims for the current post, but I've hard-coded for testing, and am not seeing any results */
'compare' => 'IN')
));
$more_like_this = new WP_Query ($args);
while ($more_like_this->have_posts()) : $more_like_this->the_post();
$star_rating = get_field('overall_score');
?>
<?php the_title(); ?>
<?php echo $star_rating ?>
<?php endwhile;
wp_reset_query();
?>
If you need a wp query to select some posts where multiple ACF checkbox options must be checked you can do like this:
// Get the array with selected options
$fields = get_field('somefield');
// First create the meta_query variable (AND can also be OR)
$meta_query = array('relation' => 'AND');
foreach( $fields as $field ){
$meta_query[] = array(
'key' => 'name_of_acf_checkbox_here',
'value' => $aim,
'compare' => 'LIKE',
);
}
// args
$args = array(
'numberposts' => -1,
'post_type' => 'postype_here',
'meta_query' => $meta_query,
);
$the_query = new WP_Query( $args );

Sort Wordpress Posts by One Custom Field , while excluding all with another value

i have my wordpress posts with two custom fields
'episode_number'
'season_number'
i want to select all posts with season_number=5(example) , and sort them by episode_number DESC
i've written this
$max_season=5;
$args = array(
'meta_key' => 'season_number',
'meta_compare' =>'==',
'meta_value' => $max_season,
'orderby' => 'episode_number',
'order' => 'DESC',
);
$wp_query = new WP_Query($args);
the selection based on season_number works , but i can't order them , with this code wordpress order them based on the time of publishing
anyone can help me?
I believe WordPress will only query the specified metadata you requested, which is key=season_number, value=5 (the season number). It will not query the post metadata for the key episode_number, so there is no way you can sort by that field directly in the SQL query.
You either need to loop the result of the query and get each item's metadata for key=episode_number and populate a new sorted array accordingly or figure out a way to query also this metadata in a single query as well.
For the second one, I have no idea how this will work.
My original answer was off the mark, I misread the question
Try something like this:
$max_season=5;
$args = array(
'meta_key' => 'episode_number',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'season_number',
'value' => array($max_season),
'compare' => 'IN',
)
)
);
$wp_query = new WP_Query($args);

Wordpress query with several meta values as condition

First time using wordpress query so not sure how to handle this problem. I want to get post titles where meta_key is 'tag' and meta_values are 'A, B, C'. Something similar to IN() function of sql query. How should I do to achieve that?
This is my code so far but it is not working as it ignores condition.
//$tags consists of my meta_value ( A, B, and C)
foreach ($tags as $input) {
$data[] = array( 'meta_key' => 'tag', 'meta_value' => $input, 'orderby' => 'post_date' );
}
$query = new WP_Query( $data );
Thanks in advance for your kind help.
Read the Custom Field Parameters section on the WordPress Codex for WP_Query.
The problem is you are rebuilding your entire $data array on each loop. This passes invalid parameters to WP_Query. So I imagine your getting undefined results.
You simply want to set meta_value directly or specify a meta_query parameter similar to the IN clause you described.
Here is the answer:
$args = array(
'meta_query' => array(
array(
'key' => 'tag',
'value' => $tags,
'compare' => 'IN'
)
),
'orderby' => 'post_date'
);

Categories