用于自定义帖子类型的MySQL SELECT自定义字段(post_meta)

时间:2019-01-05 22:16:57

标签: php mysql wordpress custom-post-type advanced-custom-fields

我正在尝试查询Wordpress帖子。

我创建了一个自定义帖子类型People。 每个people帖子都有自定义字段nameagelocationbirthday等。使用高级自定义字段插件创建自定义字段。

我想查询People自定义帖子类型的所有自定义字段。

我想要这样的输出:

+----+-------------+-----------+--------+-----------------------------+----------+-----+
| id | post_title  | name          | age    | location                    | birthday   | 
+----+-------------+-----------+--------+-----------------------------+----------+-----+
|  1 | SAMPLE      | some_name     | XX     | sample_location             | 10/07/1980 |
|  1 | SAMPLE      | some_name     | XX     | sample_location             | 10/07/1980 |
|  1 | SAMPLE      | some_name     | XX     | sample_location             | 10/07/1980 |
|  1 | SAMPLE      | some_name     | XX     | sample_location             | 10/07/1980 |
|  1 | SAMPLE      | some_name     | XX     | sample_location             | 10/07/1980 |
+----+-------------+-----------+--------+-----------------------------+----------+-----+

执行此操作的正确语法是什么?

我尝试过:

SELECT * 
FROM  `wp_posts` ,  `wp_postmeta` 
WHERE  `post_type` =  'people'

但是,此列表列出了所有wordpress常规发布字段。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

这是任何人可能遇到相同问题的解决方案!

SELECT posts_people.ID AS people_ID,
   posts_people.post_title AS people_post_title,
   (select meta_value from wp_postmeta where meta_key = 'name' AND post_id = posts_people.ID) as name,
   (select meta_value from wp_postmeta where meta_key = 'age' AND post_id = posts_people.ID) as age,
   (select post_title from wp_posts where ID = SUBSTRING_INDEX(SUBSTRING_INDEX((select meta_value from wp_postmeta where meta_key = 'location' AND post_id = posts_people.ID),'";',1),':"',-1)) as location,
   (select meta_value from wp_postmeta where meta_key = 'birthday' AND post_id = posts_people.ID) as stelexos_kinito
FROM wp_posts AS posts_people
WHERE post_type = 'people' and post_status = 'publish'

答案 1 :(得分:-1)

首先,您要从两个表中进行选择,而无需连接或设置它们之间的关系(将每个数据集连接到另一个表应该是一种关系)

您可以执行以下操作:

SELECT t1.*, t2.* 
FROM posts as t1 
INNER JOIN postmeta as t2 
ON t1.ID = t2.post_id 
WHERE t1.post_type = 'people' 
AND t2.meta_key = 'name'

**注意:您应该注意表名,并根据需要在查询中替换表中的列名。