如何通过SQL查询显示多个Post meta_key/meta_Value

时间:2017-01-10 作者:Jnsn_

我还没有找到通过SQL查询帖子来显示多个Posteta meta\\u key/meta\\u值的解决方案。我正在另一个网站上使用高级自定义字段(ACF)插件,并试图将帖子的内容拉到另一个网站上。除了不能显示更多的meta\\u值外,所有内容都显示得很好。

这是我的代码:

$mydb = new wpdb(\'database_name\',\'database_user\',\'database_pw\',\'database_host\');
    $rows = $mydb->get_results("
        SELECT P.ID, P.post_title, P.post_content, P.post_author, meta_value
        FROM wp_posts AS P
        LEFT JOIN wp_postmeta AS PM on PM.post_id = P.ID 
        WHERE P.post_type = \'post\' and P.post_status = \'publish\'

        and meta_key = \'job_title\'
        and meta_key = \'company_email\' //2nd meta_key I need to work

        ORDER BY P.post_date DESC
        ");

foreach ($rows as $row) :
    echo $row->meta_value;
endforeach;
如您所见,我只能检索一个meta\\u键/meta\\u值,但要显示多个字段。

1 个回复
最合适的回答,由SO网友:Kudratullah 整理而成

将where子句更改为or

SELECT P.ID, P.post_title, P.post_content, P.post_author, meta_value
FROM wp_posts AS P
LEFT JOIN wp_postmeta AS PM on PM.post_id = P.ID
WHERE P.post_type = \'post\' and P.post_status = \'publish\' and ( meta_key = \'job_title\' or meta_key = \'company_email\' )
ORDER BY P.post_date DESC
但是这个sql将在2行中为您的元键和值返回相同的帖子;你会得到这样的结果

+-----+------------+--------------+-------------+----------+------------+
| ID  | post_title | post_content | post_author | meta_key | meta_value |
+-----+------------+--------------+-------------+----------+------------+
| 10  | Post Title | Post Content |           1 |   key1   |   value1   |
+-----+------------+--------------+-------------+----------+------------+
| 10  | Post Title | Post Content |           1 |   key2   |   value2   |
+-----+------------+--------------+-------------+----------+------------+
如果需要将元键作为列,将元值作为对应列的值,则需要将行旋转到列

SELECT P.ID, P.post_title, P.post_content, P.post_author,
    MAX(IF(PM.meta_key = \'job_title\', PM.meta_value, NULL)) AS job_title,
    MAX(IF(PM.meta_key = \'company_email\', PM.meta_value, NULL)) AS company_email
FROM wp_posts AS P
LEFT JOIN wp_postmeta AS PM on PM.post_id = P.ID
WHERE P.post_type = \'post\' and P.post_status = \'publish\'
ORDER BY P.post_date DESC
这将返回一行结果,如下所示

+-----+------------+--------------+-------------+-----------+---------------+
| ID  | post_title | post_content | post_author | job_title | company_email |
+-----+------------+--------------+-------------+-----------+---------------+
| 10  | Post Title | Post Content |           1 | job title | company@email |
+-----+------------+--------------+-------------+-----------+---------------+

相关推荐

无法在模板函数.php中使用IS_HOME

我试图在标题中加载一个滑块,但只在主页上加载。如果有帮助的话,我正在使用Ultralight模板。我正在尝试(在template functions.php中)执行以下操作:<?php if ( is_page( \'home\' ) ) : ?> dynamic_sidebar( \'Homepage Widget\' ); <?php endif; ?> 但这行不通。现在,通过快速的google,我似乎需要将请