简体   繁体   中英

Get Wordpress posts that match 2 different categories via custom SQL statement

I'm looking to write a custom SQL statement that will pull published posts from a Wordpress DB that match 2 different categories.

Category 1 (Static) = "Website-1"
Category 2 (Dynamic) = "News", "Tips", "Recreation", etc.

This is a little out of my realm so any help would be greatly appreciated.
This is what I have so far:

select p.* from wp_terms wt
    join wp_term_taxonomy t on wt.term_id = t.term_id
    join wp_term_relationships wpr on wpr.term_taxonomy_id = t.term_taxonomy_id
    join wp_posts p on p.id = wpr.object_id
where
    t.taxonomy = 'category' and
    wt.name = 'Website-1' and
    p.post_status = 'publish'
group by p.id
order by p.post_date desc
limit 10

It will pull the first category no problem but I need it to match on 2 categories.

Any insight would be greatly appreciated.

Thanks!

The solution I came up with:

select p.* from wp_posts p 
join wp_term_relationships tr on p.id = tr.object_id
join wp_term_taxonomy tt on tt.term_taxonomy_id = tr.term_taxonomy_id
join wp_terms t on t.term_id = tt.term_id

where p.id in 
    (select tr2.object_id from wp_term_relationships tr2
     join wp_term_taxonomy tt2 on tt2.term_taxonomy_id = tr2.term_taxonomy_id
     join wp_terms t2 on t2.term_id = tt2.term_id
     where 
     tt2.taxonomy = 'category' and
     t2.name in ('Website-1') and
     p.id = tr2.object_id
) and
p.post_status = 'publish' and
tt.taxonomy = 'category' and
t.name in ('News')
group by p.id
order by p.post_date desc
limit 10

I'm sure there's a better way to write this query since it's pretty messy but it works for now.

Try having instead of where after group by. I would add this as question / comment but I don't have enough points... what happens if you switch the order of the categories?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM