获取标签和类别帖子WP SQL

时间:2017-04-30 11:20:42

标签: sql wordpress

我是ios开发人员,并且在查询时遇到了一些问题。

我通过以下查询获得wordpress帖子:

SELECT id, post_title, post_content FROM `posts` 
WHERE post_status = 'publish' AND post_type = 'post';

但我需要获得一些标签帖子和类别帖子,如:

SELECT id, post_title, post_content FROM `posts` WHERE category = '1';

SELECT id, post_title, post_content FROM `posts` WHERE tag = '1';

我得到的标签和类别都在terms表中。如何连接两个表并获得所需的帖子。

1 个答案:

答案 0 :(得分:0)

您需要查看wp_terms表以获取标记的term_id,然后查看wp_term_taxonomy表以转换为term_taxonomy_id。然后,可以使用它来过滤wp_term_relationships表以获取post id列表。下面是一些SQL,用于从标签或类别名称中获取帖子ID列表

SELECT object_id FROM wp_term_relationships 
INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id
INNER JOIN wp_terms ON wp_terms.term_id=wp_term_taxonomy.term_id 
WHERE name='tag,category'

要获得实际帖子,您可以使用每个object_id来过滤wp_posts,例如

SELECT ID,post_title,post_content FROM wp_posts WHERE ID='object_id' 

或者您可以在一个查询中执行此操作以获取具有指定标记,类别

的所有帖子
SELECT ID,post_title,post_content FROM wp_posts 
INNER JOIN wp_term_relationships ON wp_term_relationships.object_id=wp_posts.ID
INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id
INNER JOIN wp_terms ON wp_terms.term_id=wp_term_taxonomy.term_id 
WHERE name='tag,category'