【问题标题】:how do i get only 1 post from each category in wordpress我如何从 wordpress 中的每个类别中仅获得 1 个帖子
【发布时间】:2011-03-16 21:54:15
【问题描述】:

我有一个名为新闻的类别,其中包含许多子类别。 我想做的是从每个子类别(包括类别标题、帖子标题、附件图片)中仅获取 1 个帖子(最新)。 朋友们有什么建议吗??

【问题讨论】:

  • 这是您关于 SO 的第 6 个问题,您还没有接受任何以前的答案。如果有任何有用的答案,请这样做,这将改善你的业力:)

标签: wordpress categories posts


【解决方案1】:
<?php

$news_cat_ID = get_cat_ID( 'News' ); 
$news_cats   = get_categories( "parent=$news_cat_ID" );
$news_query  = new WP_Query;

foreach ( $news_cats as $news_cat ) :
    $news_query->query( array(
        'cat'                 => $news_cat->term_id,
        'posts_per_page'      => 1,
        'no_found_rows'       => true,
        'ignore_sticky_posts' => true,
    ));

    ?>

    <h2><?php echo esc_html( $news_cat->name ) ?></h2>

    <?php while ( $news_query->have_posts() ) : $news_query->the_post() ?>

            <div class="post">
                <?php the_title() ?>
                <!-- do whatever you else you want that you can do in a normal loop -->
            </div>  

    <?php endwhile ?>

<?php endforeach ?>

【讨论】:

  • 谢谢你 THEDeadMedic。它起作用了,你能帮我另一个吗? (扩展相同的代码)我如何只显示那些有图片附件并按日期排序的帖子
  • 如何在单个 SQL 查询中做到这一点?
  • 它有效,但我们不能通过这种方式按日期排序帖子。正如@SaeeshTendulkar 所问,我想找到一个使用单个 SQL 查询的解决方案,这样会更干净
【解决方案2】:

几个小时后,感谢我们遍布全球的伙伴,我已经能够修改主查询,因此我们甚至不需要使用模板并生成新的查询和循环...

// My function to modify the main query object
function grouped_by_taxonomy_main_query( $query ) {

    if ( $query->is_home() && $query->is_main_query() ) { // Run only on the homepage

        $post_ids = array();

        $terms = get_terms('formato');

        foreach ( $terms as $term ) {
            $post_ids = array_merge( $post_ids, get_posts( array( 
                'posts_per_page' => 4, // as you wish...
                'post_type' => 'video', // If needed... Default is posts
                'fields' => 'ids', // we only want the ids to use later in 'post__in'
                'tax_query' => array( array( 'taxonomy' => $term->taxonomy, 'field' => 'term_id', 'terms' => $term->term_id, )))) // getting posts in the current term
            );
        }

        $query->query_vars['post_type'] = 'video'; // Again, if needed... Default is posts
        $query->query_vars['posts_per_page'] = 16; // If needed...
        $query->query_vars['post__in'] = $post_ids; // Filtering with the post ids we've obtained above
        $query->query_vars['orderby'] = 'post__in'; // Here we keep the order we generated in the terms loop
        $query->query_vars['ignore_sticky_posts'] = 1; // If you dont want your sticky posts to change the order

    }
}

// Hook my above function to the pre_get_posts action
add_action( 'pre_get_posts', 'grouped_by_taxonomy_main_query' );

【讨论】:

  • tax_query 仅适用于自定义分类法,不适用于类别……至少我认为。这个方法我试过了,不行
猜你喜欢
  • 1970-01-01
  • 2016-10-07
  • 2011-05-16
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2016-12-25
  • 1970-01-01
相关资源
最近更新 更多