有几种方法可以做到这一点。
最简单的方法就是获取所有内容:帖子和术语,然后使用一些array_filter
将事物分组的魔法。简单示例(仅适用于PHP 5.3以上版本):
<?php
$terms = get_terms(\'your_taxonomy\');
$term_ids = array_map(function($t) {
return $t->term_id,
}, $terms);
$posts = get_posts(array(
\'nopaging\' => true,
\'tax_query\' => array(
array(
\'taxonomy\' => \'category\',
\'field\' => \'id\',
\'terms\' => $term_ids,
),
),
\'meta_query\' => array(
array(
\'key\' => \'TEST1\',
\'compare\' => \'EXISTS\', // wp 3.5+ only
)
),
));
foreach ($terms as $t) {
$posts_in_term = array_filter($posts, function($p) use ($t) {
// has_term likely triggers a DB hit...
return has_term($t->term_id, \'your_taxonomy\', $p);
});
// do stuff with $posts_in_term
}
这很容易理解。您将大量的订购工作发送到DB,并在PHP应用程序中完成。不错,DB点击率肯定比以前少了。如果你需要在每个类别名称上加一个标题,这可能是一条可行之路,因为使用下一种方法将非常困难。
选项2:执行get_posts
正常查询,但挂接到posts_groupby
和order by term ID。您需要进行一些挖掘,以找出要在中排序的表别名/名称WP_Tax_Query
类,该类根据给定集中的分类查询数创建表别名。因为我们只有一个,所以没有allias,您只需要添加$wpdb->term_relationships.object_id
发送给组。最终的结果是GROUP BY $wpdb->posts.ID, $wpdb->term_relationships.object_id
.
示例:
<?php
// our group by callback
function wpse84243_groupby($groupby, $query) {
global $wpdb;
return $groupby . \' \' . $wpdb->term_relationships . \'.object_id\';
}
add_filter(\'posts_groupby\', \'wpse84243_groupby\', 10, 2);
$posts = get_posts(array(
\'nopaging\' => true,
\'tax_query\' => array(
array(
\'taxonomy\' => \'category\',
\'field\' => \'id\',
\'terms\' => get_terms(\'category\', array(\'fields\' => \'ids\')),
),
),
\'meta_query\' => array(
array(
\'key\' => \'TEST1\',
\'compare\' => \'EXISTS\', // wp 3.5+ only
)
),
));
// remove the filter, put things back to normal
remove_filter(\'posts_groupby\', \'wpse84243_groupby\', 10, 2);
// do stuff with $posts, they\'ll be grouped by your taxonomy ID.