循环浏览4种帖子类型,每种类型只返回1个帖子

时间:2015-09-17 18:03:57

标签: wordpress loops custom-post-type wp-query

我试图了解返回4篇最新帖子的最有效方法。每个帖子类型1个。有4种帖子类型。

我可以做几件事,比如4个不同的查询。或者计算返回的每个帖子类型中的每个帖子,然后只允许第一个显示。但我提出的所有内容似乎都过于复杂。

这是我到目前为止所返回的4篇帖子,其中包括最近的任何帖子类型

    <?php 
        $newsArgs  = array(
            'posts_per_page'  => 4,
            'orderby'         => 'post_date',
            'order'           => 'DESC',
            'post_type'       => array('post', 'news', 'press', 'casestudy'),
            'post_status'     => 'publish',
            'suppress_filters' => true,
        );

        $query = new WP_Query( $newsArgs );
        if ( $query -> have_posts()) {
            while ( $query -> have_posts() ) : $query->the_post(); ?>

                    <?php the_title(); ?>

           <?php endwhile;
        }

        wp_reset_postdata(); 

    ?>
</ul>

1 个答案:

答案 0 :(得分:0)

如果没有创建自定义查询来处理这个问题(本身看起来非常难看),如果每个请求至少有4个或5个单独的查询,Wordpress就没有太多支持它的方法。 ...... very expensive

为了确保您至少获得每种帖子类型中的一种而不太关心性能,您可以执行以下操作:

$results = array();
foreach(array('post', 'news', 'press', 'casestudy') as $type){
    $post = get_posts(array(
        'posts_per_page'  => 1,
        'post_type'       => $type,
        'post_status'     => 'publish'
    ));
    $results[] = $post[0]->ID;
}
$query = new WP_Query(array(
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'suppress_filters' => true,
    'post__in'         => $results
));
if ( $query -> have_posts()) {
    while ( $query -> have_posts() ) : $query->the_post(); ?>
        <?php the_title(); ?>
    <?php endwhile;
}
wp_reset_postdata();

它未经测试,但它可以帮助您到达您需要的地方。