如何使用TAX_QUERY将每个术语的帖子限制为1条?

时间:2012-02-15 作者:Daniel Fris

每个人需要1个帖子。

<?php 

    global $post; // required

        $args = array (
            \'tax_query\' => array (
                \'relation\' => \'AND\',
                array (
                    \'taxonomy\' =>\'category\',
                    \'field\' => \'slug\',
                    \'terms\' => array (\'economy\',\'the-constitution\',\'monetary-policy\',\'liberty\')
                ),
                array (
                    \'taxonomy\' => \'highlight\',
                    \'field\' => \'slug\',
                    \'terms\' => array (\'lead\',\'featured\'),
                    \'operator\' => \'NOT IN\' 
                )
            )
        );

        $posts = get_posts($args);

        foreach ($posts as $post) {

            setup_postdata($post); ?>

            <li class="post">
                <?php if(has_post_thumbnail()): ?><div class="imgframe"><?php the_post_thumbnail(\'PostThumbSideBar\'); ?></div><?php else: endif; ?>
                <p class="meta"><?php the_category(\' \'); ?> <?php the_tags(\' \'); ?></p>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            </li>

    <?php } ?>
    <?php wp_reset_query(); // reset the query ?>

1 个回复
最合适的回答,由SO网友:Evan Yeung 整理而成

<?php
$categories = array(\'economy\',\'the-constitution\',\'monetary-policy\',\'liberty\');
foreach($categories as $category) {
    $args = array(
        \'posts_per_page\' => 1,
        \'category_name\' => $category,
        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'highlight\',
                \'field\' => \'slug\',
                \'terms\' => array( \'lead\',\'featured\' ),
                \'operator\' => \'NOT IN\'
            )
        )
    );
    $wpse42358_query = new WP_Query( $args );
    while( $wpse42358_query->have_posts() ) : $wpse42358_query->the_post();
        // write post stuff here
    wp_reset_postdata();
}
?>
我选择使用WP\\u查询,因为您可以更好地控制分类查询。

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post