PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

[FIXED] Fetch posts with attachments in a certain category?

 January 08, 2022     join, mysql, sql, wordpress     No comments   

Issue

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 post.*
FROM `bma_posts` AS post
WHERE
    EXISTS (
        SELECT 1
        FROM `bma_posts` AS attachment
        JOIN `bma_term_relationships` AS relationship ON
            relationship.`object_id` = attachment.`ID`
            AND
            relationship.`term_taxonomy_id` IN (17,15,16,5)
        WHERE
            attachment.`post_parent` = post.`ID`
            AND
            attachment.`post_type` = 'attachment'
    )
    AND
    post.`post_type` = 'post'
    AND
    post.`post_status` = 'publish'
ORDER BY post.`post_date` DESC
LIMIT 3

The problem now is that I can't get the attachment.ID to know "who" included that post on the query.


Solution

Select ...
From wp_posts As P
Where Exists    (
                Select 1
                From wp_posts As P1
                    Join wp_term_relationship As WTR1
                        On WTR1.object_id = P1.ID
                            And WTR1.term_taxonomy_id In(3)
                Where P1.post_parent = P.Id
                    And P1.post_type = 'attachment'
                )
    And P.post_type = 'post'
Order By p.post_date DESC
Limit 15    


Answered By - Thomas
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing