我有一个自定义帖子叫做“account”,自定义分类法叫做“bank”;
我想做的是用wp\\u query post显示一个帖子列表,其中应该有一个名为“tax”的特定自定义字段。
但我希望在帖子的结果列表中,对于我的自定义分类法的每个类别,只有一篇帖子(例如最后一篇)。
我的代码是:
$query = new WP_Query ( array(
\'showposts\' => 5,
\'post_type\' => \'account\',
\'meta_key\' => \'other_custom_field\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'desc\',
\'meta_query\' => array(array(\'key\' => \'tax\',\'compare\' => \'=\',\'value\' => 0)), ) );
此代码可以工作,但它显示了每个自定义帖子类别中包含相同自定义字段“tax”的所有帖子。
我想为每个类别只显示一篇文章,使用这个值的自定义字段。
SO网友:Max Yudin
<?php
// get all terms of the `bank` taxonomy
$banks = get_terms(
array(
\'taxonomy\' => \'bank\',
// more arguments can be used, see (1) below the code
)
);
// look through banks, picking one post from each
foreach ( $banks as $bank ) {
$args = array(
\'post_type\' => \'account\', // your custom post type
\'posts_per_page\' => \'1\', // one post per bank (per term)
\'tax_query\' => array(
array(
\'taxonomy\' => \'bank\',
\'terms\' => $bank->term_id,
),
)
\'meta_query\' => array( // your custom field stuff
array(
\'key\' => \'tax\',
\'compare\' => \'=\',
\'value\' => 0,
),
),
// more arguments can be used, see (2) below the code
);
// The Loop
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
/*
Your markup goes here
*/
the_ID();
the_title();
}
}
} // END foreach bank
此外,这里应该是错误检查,但它超出了问题的范围。
有关可接受的参数,请参阅:
- WP_Term_Query.
- WP_query