首页 > 解决方案 > Mysql SELECT自定义字段(post_meta)用于自定义帖子类型

问题描述

我正在尝试查询 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 常规帖子字段。

有人可以帮忙吗?

标签: phpmysqlwordpresscustom-post-typeadvanced-custom-fields

解决方案


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

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'

推荐阅读