【问题标题】:Mysql SELECT custom fields (post_meta) for custom post typeMysql SELECT自定义字段(post_meta)用于自定义帖子类型
【发布时间】:2019-06-01 01:53:52
【问题描述】:

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

有人可以帮忙吗?

【问题讨论】:

  • 你问的是查询wordpress元数据库,你甚至没有在你的问题中提到“Wordpress”这个词?!描述性以找到正确的答案
  • 你是想在前端显示这种格式还是只想正确查询数据库???
  • 我使用了一个可以在前端显示的插件。我只需要正确查询数据库。
  • @TanmayPatel 你能帮忙吗?
  • @Christoforos A 能否请您与我分享前端链接,以便我为您提供帮助。

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


【解决方案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'

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

【讨论】:

  • 您好,感谢您的回复。所以我可以使用上面的代码只改变 post_type 和 meta_key??还是我必须修改更多?
  • 我留下 post_type 和 meta_key 就像你的一样,尝试对你的数据库执行它
  • 我得到一个错误 MySQL 说:表 'admin_wp24.posts' 不存在
  • @ChristoforosA - 请记住,就像注释中所说,您可能有标题为 wp_postswp_postmeta 的表格。记得做相应的改变。
【解决方案2】:

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

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'

【讨论】:

    猜你喜欢
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2014-03-02
    • 2021-11-26
    • 2018-01-29
    相关资源
    最近更新 更多