从分类中获取最新帖子

时间:2014-10-09 作者:John Robertson

我有三个类别:旅行、目的地和小费。我一直在尝试从每个类别中获取最新的帖子,然后将它们放入一个数组中。以下是我的想法。

//GET CATEGORIES
//I have this code but this only selects one category
$args = array ( \'post_per_page\' => 1, \'cat\' => 16 ); 

//SELECT THE LATEST POST FROM EVERY CATEGORY
//This part I don\'t know what to do.

//GET ID OF THE POST SO THAT I CAN ADD IT TO THE ARRAY
$post   = array(); <-- This should contain every latest post from the categories.
$post[] = get_post( /*ID OF THE POST SHOULD BE HERE*/ );
我想要实现的是获得数组中每个类别的最新帖子的id。请帮忙。非常感谢。

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

好的,您可以使用foreach循环返回每个类别的最新帖子。以下是您应该如何做到这一点。

<?php

    $postids = array();
    $catids = array( 1, 2, 3 ); // add category ids here.

    foreach ( $catids as $catid ) {

        $my_query = new WP_Query( array( \'cat\' => $catid, \'ignore_sticky_posts\' => 1, \'posts_per_page\' => 1, \'no_found_rows\' => true, \'update_post_term_cache\' => false, \'update_post_meta_cache\' => false ) );

        if ( $my_query->have_posts() ) :

            while ( $my_query->have_posts() ) : $my_query->the_post();
                $postids[] = $post->ID;
            endwhile;

        endif;

        wp_reset_postdata();

    }

    print_r( $postids ); // printing the array.

?>
这实际上与运行3个不同的循环相同,但现在代码更干净了。

结束