在WordPress中显示甚至奇数位置的不同类别的帖子

时间:2016-12-28 11:27:59

标签: php wordpress

我需要在WordPress中以不同类别的偶数或奇数标准显示数据。例如,一个新闻类型的帖子,另一个是第二类。

我用于显示的代码

$wp_query_array = null; 
$array1 = array('post_type' => array("post"),'posts_per_page' =>5);
$array2 = array('post_type' => array("news"),'posts_per_page' =>5); 
$posts = get_posts($array1); $news = get_posts($array2);

echo "<pre>";

foreach($posts as $key => $row){ 
  echo $posts[$key]->post_type;
  echo $news[$key]->post_type; echo "<br>"; 
}

您也可以在此处找到此代码:

http://laravel.io/bin/jQ8r9#7,15-16

1 个答案:

答案 0 :(得分:1)

创建一个wp_query的两个对象,它们在主循环内迭代。当计数器变为偶数时,它会显示post,否则显示新闻。

$post_data = array('post_type' => 'post','posts_per_page' =>5);
$news_data = array('post_type' => 'news','posts_per_page' =>5);


$post_arr = new WP_Query($post_data);
$news_arr = new WP_Query($news_data);

// counter variable

$postcount=0;

// get how many post in object

$total_post_count = ($post_arr->post_count)+($news_arr->post_count);

//Main while loop we can say container

while($postcount < $total_post_count) :

            if($postcount %2 == 0):

                        //This show post

                        while ( $post_arr->have_posts() ) : $post_arr->the_post();
                            echo '<li>';
                            $post_arr->the_title();
                            echo '</li>';
                        endwhile;

            else:
                        //This show news

                        while ( $news_arr->have_posts() ) : $news_arr->the_post();
                            echo '<li>';
                            $news_arr->the_title();
                            echo '</li>';
                        endwhile;
            endif;
endwhile;