0

I have a bunch of posts belonging to category 6, each having the same meta fields. I'm interested in two fields in particular: "pce_monday_open" and "pce_monday_close", both of which have numeric values.

I want to run a query_posts() query that returns posts in category 6, and where some number, $pce_time, is in between the values of the two meta fields. My current query argument is:

$pce_arg = array(
'cat' => 6,
'meta_query' => array(
array('key' => 'pce_monday_open', 'value' => $pce_time, 'compare' => '<=' ),
array('key' => 'pce_monday_close', 'value' => $pce_time, 'compare' => '>=' )
)
);

Unfortunately this doesn't seem to be working, and no posts are being returned. My search seems to work fine with other query parameters (such as searching other meta fields for an exact match), so I think there is an issue with my comparison parameters.

Is there something obviously wrong with what I've written? Or is it correct, and the issue might lie elsewhere?

1 Answer 1

0

First, do not query_posts; use WP Query instead. That being said, I assume that pce_monday_open is lower than pce_monday_close and that you want posts between pce_monday_open and pce_monday_close, so I think your comparison logic is wrong. Also, you may need to set the relationship between the two meta query arrays:

$pce_arg = array(
    'cat' => 6,
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key'     => 'pce_monday_open',
            'value'   => $pce_time,
            'compare' => '<=' ),
        array('
            key'      => 'pce_monday_close',
            'value'   => $pce_time,
            'compare' => '>='
        )
    )
);

$query = new WP_Query( $pce_arg );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        //Loop on each post
    }
} else {
    // no posts found
}

wp_reset_postdata();
1
  • Thanks for the reply cybmeta. "pce_monday_open" is indeed lower than "pce_monday_close", however I don't understand why you'd switch the comparison operators. Take the following meta query: array('key' => $metakey, 'value' => $metavalue, 'compare'=> '>=') Will this not return posts where the $metakey field has a value greater than or equal to $metavalue? If so, then what I had made sense I think, because I wanted the value of pce_monday_open to be less than $pce_time and pce_monday_close to be greater. Thanks for your other comment about WP_query too!
    – Dan
    Commented Jan 6, 2015 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.