Fetch posts with attachments in a certain category?

Posted by TiuTalk on Stack Overflow See other posts from Stack Overflow or by TiuTalk
Published on 2010-05-20T22:50:59Z Indexed on 2010/05/20 23:50 UTC
Read the original article Hit count: 334

Filed under:
|
|
|
|

I need to retreive a list of posts that have (at least) one attachment that belongs to a category in WordPress.

The relation between attachments and categories I made by myself using the WordPress default method.

Here's the query that i'm running right now:

SELECT p.*
FROM `wp_posts` AS p # The post
    INNER JOIN `wp_posts` AS a # The attachment
        ON p.`ID` = a.`post_parent`
        AND a.`post_type` = 'attachment'
    INNER JOIN `wp_term_relationships` AS ra
        ON a.`ID` = ra.`object_id`
        AND ra.`term_taxonomy_id` IN (3) # The category ID list
WHERE p.`post_type` = 'post'
ORDER BY p.`post_date` DESC
LIMIT 15

The problem here is that the query only use the first found attachment, and if it doesn't belongs to the category, the result isn't returned.

© Stack Overflow or respective owner

Related posts about mysql

Related posts about sql