使用全局$wpdb对类别和页面进行自定义查询;

时间:2013-08-27 作者:amespower

我有一个返回类别的自定义查询,但我还需要返回一些带有特定帖子ID的页面。我该如何添加这些内容?它们显然没有分类法,是页面文章类型。

以下是我目前的查询:

protected function _getPostByCategory($category) {
global $wpdb;

$result = $wpdb->get_results(" SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->terms.name = \'$category\'
AND $wpdb->term_taxonomy.taxonomy = \'category\'
AND $wpdb->posts.post_status = \'publish\'
AND $wpdb->posts.post_type = \'post\'
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.post_date DESC");

2 个回复
SO网友:user2753996

使用工会怎么样?举个例子:

(SELECT * FROM $wpdb->posts (with JOIN and WHERE as needed))

UNION

(SELECT * FROM $wpdb->posts (with WHERE to select pages)) 

GROUP BY/ORDER BY
select必须在括号中,才能对整个联合结果使用order by。

作为第二种选择,您可以使用插件来启用页面上的类别和标记,我多次使用它对类别中的页面进行分类。

要在WordPress“init”hook上激发的调用是:

register_taxonomy_for_object_type(\'category\', \'page\');
在编辑页面时,你会有一个经典的类别选择器,就像普通帖子一样。

SO网友:epilektric

我不是MySQL查询专家OR 语句可能会起作用。

OR $wpdb->posts.ID = 2
OR $wpdb->posts.ID = 703
AND $wpdb->posts.post_status = \'publish\'
AND $wpdb->posts.post_type = \'page\'
所以在您的查询上下文中是这样的。

$result = $wpdb->get_results(" SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->terms.name = \'$category\'
AND $wpdb->term_taxonomy.taxonomy = \'category\'
AND $wpdb->posts.post_status = \'publish\'
AND $wpdb->posts.post_type = \'post\'

OR $wpdb->posts.ID = 2
OR $wpdb->posts.ID = 703
AND $wpdb->posts.post_status = \'publish\'
AND $wpdb->posts.post_type = \'page\'

GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.post_date DESC");

结束

相关推荐

如何访问由QUERY_POST返回的特定帖子?

具体来说,我带回了A类中最近的7篇文章,但我想把第一篇文章的缩略图放进去<div id=A> 第二篇文章的缩略图<div id=B> 这七个帖子也是如此。如果这是一个数组,我只需使用<div>, 但我不知道在我用query\\u帖子带回这些帖子后,如何访问这些帖子。有什么想法吗?