Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am trying to return posts that contain meta value and ones that don't in one query. Is this possible?

So in plain English, I am trying to get posts that have a meta key of date and value of date and posts that don't have date set as well.

This is what I have so far and it isn't working. UPDATED - i have now added another meta to the post to make it easier...I added no-date meta so instead of checking for it being empty, I am checking if no-date is set. So my revised code now looks like this but I can't seem to order it now.

 $args = array(
            'cat' => $type,
            'post_status' => 'publish',
            'post_type' => 'post',
            'paged' => get_query_var('paged'),
            'posts_per_page' => 10,
                    'orderby' => 'meta_value',
            'meta_query' => array(
                    'relation' => 'OR',
                    array('key' => 'date', 'value' => date('m-d-Y'), 'compare' => '>=', 'type' => 'char'),
                    array('key' => 'no-date', 'value' => '1', 'compare' => '=')
                    )

        );

So now this "seems" to return what i want...however I can't seem to sort it using orderby...I want the date to be closet first and future date last and for the no-dates ones to come after the ones with date via the post date.

Thanks...

share|improve this question

1 Answer 1

You use both 'meta_key' and 'meta_query' - it is a wrong usage. Remove this code:

'meta_key' => 'date',

and try again.

After remove $cat WP produce sql query:

SELECT SQL_CALC_FOUND_ROWS  wp_posts.*
FROM wp_posts
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
AND (
  (
    wp_postmeta.meta_key = 'date'
    AND CAST( wp_postmeta.meta_value AS CHAR) >= '03-17-2012'
  )
  OR (mt1.meta_key = 'no-date' AND CAST(mt1.meta_value AS CHAR) = '1' )
)
GROUP BY wp_posts.ID
ORDER BY post_date desc
LIMIT 0, 10

If You have no results, check your data, because query is correct.

share|improve this answer
    
and I tried that before...without it, I can't set the orderby...according to the codex, meta_key must be set to have orderby...thanks for the reply though.. –  Rick Mar 16 '12 at 23:55
    
Please see updated code which "seems" to work now but I can't order it like I could if I did a simple one criteria. –  Rick Mar 17 '12 at 0:09
    
What dou you have in "cat" param? –  Marcin Mar 17 '12 at 6:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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