因此,首先,我会使用get_posts
而不是编写自己的查询。
策略:一次获取所有帖子,然后使用回调或foreach
循环。下面是一个PHP 5.3+示例(匿名函数等)。
让我们将所有这些都封装在一个函数中,该函数将采用post类型、所需的术语以及它们所属的分类法。
<?php
function wpse63444_get_posts($post_type, $terms, $tax)
{
}
这样我们就可以拿到帖子了。
<?php
function wpse63444_get_posts($post_type, $terms, $tax)
{
$posts = get_posts(array(
\'post_type\' => $post_type,
\'meta_key\' => \'number\', // the meta key
\'order_by\' => \'meta_value_num\',
\'order\' => \'ASC\', // might have to tweak the order a bit
\'numberposts\' => -1, // get ALL THE POSTS
\'tax_query\' => array(
array(
\'taxonomy\' => $tax,
\'field\' => \'slug\',
\'terms\' => $terms,
\'include_children\' => false,
),
),
));
if(!$posts)
return array(); // bail if we didn\'t get any posts
}
现在我们已经有了所有的帖子,并且知道了术语,我们可以将它们过滤到一组术语=>帖子对中。
<?php
function wpse63444_get_posts($post_type, $terms, $tax)
{
// snip snip
$res = array();
foreach($terms as $t)
{
// PHP < 5.3 will need something different here
$res[$t] = array_filter($posts, function($p) use ($t, $tax) {
if(has_term($t, $tax, $p))
return $p; // the post has this term, use it
});
}
return $res;
}
整个功能:
<?php
function wpse63444_get_posts($post_type, $terms, $tax)
{
$posts = get_posts(array(
\'post_type\' => $post_type,
\'meta_key\' => \'number\', // the meta key
\'order_by\' => \'meta_value_num\',
\'order\' => \'ASC\', // might have to tweak the order a bit
\'numberposts\' => -1, // get ALL THE POSTS
\'tax_query\' => array(
array(
\'taxonomy\' => $tax,
\'field\' => \'slug\',
\'terms\' => $terms,
\'include_children\' => false,
),
),
));
if(!$posts)
return array(); // bail if we didn\'t get any posts
$res = array();
foreach($terms as $t)
{
// PHP < 5.3 will need something different here
$res[$t] = array_filter($posts, function($p) use ($t, $tax) {
if(has_term($t, $tax, $p))
return $p; // the post has this term, use it
});
}
return $res;
}
中的一些普通帖子和类别的用法示例
theme unit test 数据
<?php
$res = wpse63444_get_posts(\'post\', array(\'cat-a\', \'cat-b\', \'cat-c\'), \'category\');
if($res)
{
foreach($res as $cat => $posts)
{
if(!$posts)
continue;
echo \'<h1>\', get_term_by(\'slug\', $cat, \'category\')->name, \'</h1>\';
foreach($posts as $p)
echo \'<h2>\', $p->post_title, \' \', get_post_meta($p->ID, \'number\', true), \'</h2>\';
}
}
下面是封装在
plugin