如何为包含特定自定义字段的自定义帖子的每个分类仅显示一个帖子

时间:2018-01-09 作者:Giulio

我有一个自定义帖子叫做“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”的所有帖子。

我想为每个类别只显示一篇文章,使用这个值的自定义字段。

1 个回复
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
此外,这里应该是错误检查,但它超出了问题的范围。

有关可接受的参数,请参阅:

  1. WP_Term_Query.
  2. WP_query

结束

相关推荐

WP_LIST_CATEGORIES()-将div添加到每个li?

我正在使用wp_list_categories() 从特定的作者ID打印出每个类别的链接,这很好。然而,我还想添加一个div 致各li 将保留类别的图标。我怎样才能做到这一点?这是我当前的代码:<?php // Display a list of all categories associated with author $cat_array = array(); $args = array( \'author\' =>