Mysql: Using "AND" Operation on tags and categories tables in WordPress
العربية
български
català
中文
čeština
dansk
Nederlands
eesti
suomi
français
Deutsch
Ελληνικά
עברית
हिंदी
magyar
Bahasa Indonesia
italiano
日本語
한국어
latviešu
lietuvių
norsk
polski
Português
română
русский
slovenčina
slovenski
español
svenska
ไทย
Türkçe
українська
Tiếng Việt
This is a very specific question regarding mysql as implemented in WordPress.
I'm trying to develop a plugin which will show (select) posts that have specific 'tags' and belong to specific 'categories' (both multiple)
I was told it's impossible because the way categories and tags are stored:
- wp_posts contains a lists of post, each posts have an "ID"
- wp_terms contains a list of terms (both categories and tags). Eac term has a TERM_ID
- wp_term_taxonomy has a list of terms with their TERM_IDs and has a Taxonomy definition for each one of those (either a Category or a Tag)
- wp_term_relationship has associations betweens terms and posts
How can I join the tables to get all posts with tags "Nuclear" and "Deals" that also belong to the category "Category1" ?
Thanks!
Answer |
I misunderstood you. I thought you wanted Nuclear or Deals. The below should give you only Nuclear and Deals.
select p.* from wp_posts p, wp_terms t, wp_term_taxonomy tt, wp_term_relationship tr, wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2 wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2
where p.id = tr.object_id and t.term_id = tt.term_id and tr.term_taxonomy_id = tt.term_taxonomy_id
and p.id = tr2.object_id and t2.term_id = tt2.term_id and tr2.term_taxonomy_id = tt2.term_taxonomy_id
and p.id = tr3.object_id and t3.term_id = tt3.term_id and tr3.term_taxonomy_id = tt3.term_taxonomy_id
and (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1') and (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name = 'Nuclear') and (tt3.taxonomy = 'post_tag' and tt3.term_id = t3.term_id and t3.name = 'Deals')