wordpress custom mysql query to get only posts if a specific meta_key does not exists

I am trying to get the wp posts using custom query. Here is sql query:

SELECT p.*, IFNULL(SUM(vote), 0) AS vote_count, CAST(m.meta_value AS SIGNED) AS idea_count
FROM wp_posts p
INNER JOIN wp_term_relationships r ON p.ID=r.object_id
INNER JOIN wp_term_taxonomy t ON t.term_taxonomy_id=r.term_taxonomy_id AND t.taxonomy='category'
LEFT JOIN wp_wdpv_post_votes v ON v.post_id=p.ID
LEFT JOIN wp_postmeta m ON m.post_id=p.ID AND m.meta_key='ideas_count'
WHERE p.post_status='publish' AND p.post_type='post' AND t.term_id='5'
GROUP BY p.ID
ORDER BY p.ID DESC
LIMIT 0, 8

This sql query is working fine. But now i have another case, Where I want show the posts using this query but only the posts which does not have specific meta key. Meta key to filter is

Read More
'private_spaces_post'

This could be specific to mysql query. But i will be very thankful if someone can give me a solution for this problem.

Related posts

Leave a Reply

1 comment

  1. You can LEFT JOIN against a subquery which only returns those that do have private_spaces_post, and look for NULLs

    SELECT p.*, IFNULL(SUM(vote), 0) AS vote_count, CAST(m.meta_value AS SIGNED) AS idea_count
    FROM wp_posts p
      INNER JOIN wp_term_relationships r ON p.ID=r.object_id
      INNER JOIN wp_term_taxonomy t ON t.term_taxonomy_id=r.term_taxonomy_id AND t.taxonomy='category'
      LEFT JOIN wp_wdpv_post_votes v ON v.post_id=p.ID
      LEFT JOIN wp_postmeta m ON m.post_id=p.ID AND m.meta_key='ideas_count'
      /* LEFT JOIN subquery returning only ids that *do* have the meta key */
      LEFT JOIN (
        SELECT post_id FROM wp_postmeta WHERE meta_key='private_spaces_post'
      ) psp ON p.ID = psp.post_id
    WHERE p.post_status='publish' AND p.post_type='post' AND t.term_id='5'
      /* And find post ids from the main table that *don't* have a match in the subquery (LEFT JOIN returns NULL) */
      AND psp.post_id IS NULL
    GROUP BY p.ID
    ORDER BY p.ID DESC
    LIMIT 0, 8