- This topic is empty.
-
AuthorPosts
-
February 29, 2012 at 11:26 pm #36923
clintnelson
MemberTrying to work out how to do a meta_query with And / OR options.
I have a custom post type with a post_meta of ‘available’ which can have either a select number of months (e.g. Jan, Feb, Mar, Apr) or ‘Year Round’.
The task in hand is to create a display of the custom post types that meet certain criteria. First there is a section called New This Month where its a simple check to see if the custom post type was available this month but wasn’t available last. This code works fine for this problem
$args = array(
'post_type'=>'seedling_variety',
'meta_query' => array(
'relation' => 'AND',
array (
'key' => 'seedling_available',
'value' => serialize(strval($thismonth)),
'compare' => 'LIKE'
),
array (
'key' => 'seedling_available',
'value' => serialize(strval($lastmonth)),
'compare' => 'NOT LIKE'
)
)
);
$wp_query = new WP_Query( $args );OK, now onto the harder bit – next in turn is Still Available where the code has to check if the custom post type was available both last month AND this month OR year round. I think I’m right in saying that you can’t mix and match AND and OR relations in a query of this type and can’t think how to resolve this. The code I currently have is
$args = array(
'post_type'=>'seedling_variety',
'meta_query' => array(
'relation' => 'OR',
array (
'key' => 'seedling_available',
'value' => serialize(strval($thismonth)),
'compare' => 'LIKE'
),
array (
'key' => 'seedling_available',
'value' => serialize(strval(All)),
'compare' => 'LIKE'
)
)
);
$wp_query = new WP_Query( $args );– I’ve tried things like put an array into the first value but it doesn’t like that.
Any ideas as I’m getting nowhere fast.
March 1, 2012 at 4:33 pm #97854clintnelson
MemberThanks for the pointer Rob, I’ve gone into the brave new world of WP_Query and learnt about $wpdb->prepare and come up with the code that meets the purpose – I’ll share just for interests sake.
global $wpdb;
$thismonth = date("M");
$lastmonth = date("M",strtotime("-1 month"));
$allyear = "All";
$results = $wpdb->get_results($wpdb->prepare("
SELECT $wpdb->posts.post_title, $wpdb->posts.ID
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->postmeta.meta_key = 'seedling_available'
AND $wpdb->posts.post_type = 'seedling_variety'
AND (($wpdb->postmeta.meta_value LIKE %s) OR(($wpdb->postmeta.meta_value LIKE %s) AND ($wpdb->postmeta.meta_value LIKE %s))) ", "%$allyear%", "%$thismonth%", "%$lastmonth%"));
foreach ( $results as $post ) : setup_postdata($post);and that gives me the results I want.
-
AuthorPosts
- The forum ‘Other’ is closed to new topics and replies.