如何在 WordPress 中选择具有特定标签/类别的帖子
题
这是一个非常具体的问题 MySQL 如实施于 WordPress.
我正在尝试开发一个插件,它将显示(选择)具有特定“的帖子”标签'并且属于特定的'类别'(均为多个)
有人告诉我这是不可能的,因为类别和标签的存储方式:
wp_posts
包含一个帖子列表,每个帖子都有一个“ID”wp_terms
包含术语列表(类别和标签)。每个术语都有一个 TERM_IDwp_term_taxonomy
有一个术语列表及其 TERM_ID,并且每个术语都有一个分类定义(类别或标签)wp_term_relationships
术语和帖子之间存在关联
如何加入表格以获取带有“核”标签的所有帖子 和 “交易”也属于“Category1”类别吗?
解决方案
我误会你了。我以为你想要核或交易。下面应该只给你核和交易。
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')
其他提示
多么粗略的数据库结构啊。
不管怎样,我会做这样的事情(注意我更喜欢 EXISTS 而不是连接,但是如果你愿意,你可以将它们重写为连接;无论如何,大多数查询分析器都会将它们折叠到相同的查询计划)。您可能需要以某种方式做一些额外的杂耍才能使其发挥作用......
SELECT *
FROM wp_posts p
WHERE EXISTS( SELECT *
FROM wp_term_relationship tr
WHERE tr.object_id = p.id
AND EXISTS( SELECT *
FROM wp_term_taxonomy tt
WHERE tt.term_taxonomy_id = tr.term_taxonomy_id
AND tt.taxonomy = 'category'
AND EXISTS( SELECT *
FROM wp_terms t
WHERE t.term_id = tt.term_id
AND t.name = "Category1"
)
)
AND EXISTS( SELECT *
FROM wp_term_taxonomy tt
WHERE tt.term_taxonomy_id = tr.term_taxonomy_id
AND tt.taxonomy = 'post_tag'
AND EXISTS( SELECT *
FROM wp_terms t
WHERE t.term_id = tt.term_id
AND t.name = "Nuclear"
)
AND EXISTS( SELECT *
FROM wp_terms t
WHERE t.term_id = tt.term_id
AND t.name = "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
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 (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 in ('Nuclear', 'Deals'))
本质上,我使用了 2 个相关子表的副本 - terms、term_taxonomy 和 term_relationship。一份副本应用“类别 1”限制,另一份副本应用“核”或“交易”限制。
顺便说一句,这是一个什么样的项目,里面全都是关于核协议的帖子?你想让我们进入某个政府名单吗?;)
谢谢@Eric,它有效!只是一些代码更正以供将来参考:
- 第一个 select 语句在 wp_term_relationship tr2 之后错过了一个逗号
- 在同一选择语句中,必须更改以下内容:
wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship
tr2
应该
wp_terms t3, wp_term_taxonomy tt3, wp_term_relationship
tr3
真的很棒的答案..帮了我很多..
太棒了,它给了我构建复杂查询的基本方法!
对于像我这样的现成用户来说,有一个小修正:)
“ wp_term_relationship”将给出'不存在错误'。使用 wp_term_关系 因为它是正确的表名。
谢谢埃里克
不隶属于 StackOverflow