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'm trying to build a custom query that will return all posts that DON'T have the associated post meta. I'm not quite sure how to do this...here is what I am working with, and for your reference "score" is a custom column that I have added to the posts table.

    $querystr = "
        SELECT $wpdb->posts.ID 
        FROM $wpdb->posts, $wpdb->postmeta
        WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
        AND $wpdb->posts.post_type = 'post'
        AND $wpdb->posts.post_date < NOW()
        AND $wpdb->postmeta.meta_key != '_social_'
        ORDER BY $wpdb->posts.score DESC
        LIMIT 1
     ";

    $result = $wpdb->get_row($querystr, ARRAY_A);
    add_post_meta($result["ID"], "_social_", date("Y-m-d-H-i"), true);

The above example does not work. The context of this is that I'm running a cron to auto publish a single post to my social networks each half hour, and after I do this, I want to add the post meta _social_ so that on my next cron, I do not add it to my social networks a second time. This query, I hope, will always give me the post with the highest score that has not yet been added to my social networks.

Could anyone tell me how to query all posts that exclude the _social_ custom post meta?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

You have to do a join or a subquery:

$querystr = "
SELECT $wpdb->posts.ID 
FROM $wpdb->posts
WHERE $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_date < NOW()
AND $wpdb->posts.ID NOT IN
( SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = '_social_' )
ORDER BY $wpdb->posts.score DESC
LIMIT 1;
";
share|improve this answer
add comment

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.