2

我正在寻找编写一个自定义 SQL 查询来从我的自定义帖子类型的 6 个特定类别中的每一个中检索最新的 7 个帖子。

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

示例:如果我有类别 1、2、3、4、5、6,我想从每个类别中检索 7 个最新帖子。具体来说,查询应该提取类别 1 的 7 个最新帖子、类别 2 的 7 个最新帖子等等,所有这些都通过一个查询来完成。

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

4

1 回答 1

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
于 2011-09-15T09:18:29.570 回答