一个查询,以获取WordPress中每个类别的最新7个帖子

时间:2011-09-15 04:52:13

标签: mysql wordpress posts

我正在寻找一个单一的自定义SQL查询,以便从我自定义帖子类型的6个特定类别中检索最新的7个帖子。

我知道如何查询自定义帖子类型和分类,但我的SQL知识有限。我不知道如何让WordPress给我7个类别中的每个最新帖子7个。只要内容存在,它的返回顺序并不重要。

示例:如果我有类别1,2,3,4,5,6,我想从每个类别中检索7个最新帖子。具体来说,查询应该为类别1提取7个最新帖子,为类别2提取7个最新帖子,依此类推,只需一个查询。

我不想拥有6个单独的WP_Query实例,因为它效率不高。

1 个答案:

答案 0 :(得分:0)

你需要像下面那样使用UNION

SELECT wposts.* 
FROM $wpdb->posts wposts
    LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id 
    LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE wpostmeta.meta_key = 'customDateField'
    AND wpostmeta.meta_value >= CURDATE()
    AND $wpdb->term_taxonomy.taxonomy = 'category'
    AND $wpdb->term_taxonomy.term_id IN(1)
ORDER BY wpostmeta.meta_value ASC
LIMIT 7
UNION
SELECT wposts.* 
FROM $wpdb->posts wposts
    LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id 
    LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE wpostmeta.meta_key = 'customDateField'
    AND wpostmeta.meta_value >= CURDATE()
    AND $wpdb->term_taxonomy.taxonomy = 'category'
    AND $wpdb->term_taxonomy.term_id IN(2)
ORDER BY wpostmeta.meta_value ASC
LIMIT 7
UNION
SELECT wposts.* 
FROM $wpdb->posts wposts
    LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id 
    LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE wpostmeta.meta_key = 'customDateField'
    AND wpostmeta.meta_value >= CURDATE()
    AND $wpdb->term_taxonomy.taxonomy = 'category'
    AND $wpdb->term_taxonomy.term_id IN(3)
ORDER BY wpostmeta.meta_value ASC
LIMIT 7