我如何在Wordpress的每个类别中仅获得1个帖子 [英] how do i get only 1 post from each category in wordpress

查看:81
本文介绍了我如何在Wordpress的每个类别中仅获得1个帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a category named news and many subcategories inside it. What i wanna do is to get only 1 posts(newest) from each of those sub categories(including category title, post title, attachment image). Is there any suggestions friends??

推荐答案

<?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 ?>

这篇关于我如何在Wordpress的每个类别中仅获得1个帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆