谁能帮我显示特定自定义帖子类型的所有帖子和 Postmeta
我在 wordpress 项目中创建了一个自定义帖子类型“类(class)”,其中包含一些自定义元框
我需要显示该自定义帖子类型的所有帖子和自定义元框值
我试过下面的查询。
$query = "
SELECT $wpdb->posts.ID,$wpdb->posts.post_title,$wpdb->postmeta.meta_key
FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id)
WHERE
$wpdb->postmeta.meta_key IN ('_course_code','_instructor_name')
AND
$wpdb->posts.post_type = 'course'
";
$results = $wpdb->get_results($query);
echo "<pre>";
print_r($results);
通过对这个查询结果进行分组,它只给出一个 meta_key 值
它给了我结果:
请注意 id 和 post_title 在新索引中显示了两次
Array
(
[0] => stdClass Object
(
[ID] => 10
[post_title] => introduction to wordpress
[meta_key] => _course_code
)
[1] => stdClass Object
(
[ID] => 10
[post_title] => introduction to wordpress
[meta_key] => _instructor_name
)
[2] => stdClass Object
(
[ID] => 13
[post_title] => introduction to hacking
[meta_key] => _course_code
)
[3] => stdClass Object
(
[ID] => 13
[post_title] => introduction to hacking
[meta_key] => _instructor_name
)
)
但我期待的结果是
Array
(
[0] => stdClass Object
(
[ID] => 10
[post_title] => introduction to wordpress
[meta_key] => _course_code
[meta_key] => _instructor_name
)
[2] => stdClass Object
(
[ID] => 13
[post_title] => introduction to hacking
[meta_key] => _course_code
[meta_key] => _instructor_name
)
)
最佳答案
我自己设法得到了结果,把我的答案放在这里希望它能帮助别人。
$query = "
SELECT $wpdb->posts.ID,$wpdb->posts.post_title,
PM1.meta_value as _course_code,
PM2.meta_value as _instructor_name
FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta AS PM1 ON ( $wpdb->posts.ID = PM1.post_id AND PM1.meta_key = '_course_code')
LEFT JOIN $wpdb->postmeta AS PM2 ON ( $wpdb->posts.ID = PM2.post_id AND PM2.meta_key = '_instructor_name')
WHERE $wpdb->posts.post_type = 'course'
AND $wpdb->posts.post_status = 'publish'
AND ((PM1.meta_key = '_course_code') AND (PM2.meta_key='_instructor_name'))
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.post_date DESC
";
$results = $wpdb->get_results($query);
echo "<pre>"; print_r($results); die("here");
关于php - 显示特定自定义帖子类型的所有帖子及其帖子元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29883789/