有人可以帮我显示特定自定义帖子类型的所有帖子和帖子
我在wordpress项目中创建了一个自定义帖子类型'课程',带有一些自定义元数据框
我需要显示该自定义帖子类型的所有帖子和自定义元框值
我已尝试过以下查询。
$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
)
)
答案 0 :(得分:1)
我已经自己动手取得结果了,把答案放在这里,希望能有所帮助。
$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");
答案 1 :(得分:-1)
首先,不要做$ wpdb-&gt;帖子,因为难以阅读。其次,缺少GROUP BY sql查询部分。
$posts = $wpdb->posts;
$postmeta = $wpdb->postmeta;
$query = "SELECT $posts.ID, $posts.post_title, $postmeta.meta_key
FROM $posts
LEFT JOIN $postmeta ON ( $posts.ID = $postmeta.post_id)
WHERE
$postmeta.meta_key IN ('_course_code','_instructor_name')
AND $posts.post_type = 'course'
GROUP BY $posts.ID";
$results = $wpdb->get_results($query);
echo "<pre>";
print_r($results);
echo "</pre>";