You should change your get_posts
to WP_Query
.
You are making a lot of queries because you’re running setup_postdata
is running its own set of queries to get the post data from the posts you got through get_posts
.
This can be avoided by using WP_Query
instead.
Based on your code, you should have something like this when you change to WP_Query
<div>
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 2,
'category__in' => array( $instance['category_select'] )
);
$cnews = new WP_Query( $args );
if ( $cnews->have_posts() ) :
while ( $cnews->have_posts() ) : $cnews->the_post();
?>
// display two first posts in one css style
<?php endwhile;
wp_reset_postdata();
endif;
?>
</div>
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'offset' => 2,
'posts_per_page' => 8,
'category__in' => array($instance['category_select'])
);
$cnews = new WP_Query( $args );
$i = 0;
if ( $cnews->have_posts() ) :
while ( $cnews->have_posts() ) : $cnews->the_post();
if ($i == 0) {
echo '<div">';
echo '<ul>';
}
?>
// display eight next posts in other css style
<?php
$i++;
if ($i == 2) {
$i = 0;
echo '</div>';
}
endwhile;
wp_reset_postdata();
endif;
if ($i > 0) {
echo '</div>';
}
echo '</ul>'
?>
UPDATE
To reduce it to one query, you can do something like:
<div>
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
'category__in' => array( $instance['category_select'] )
);
$cnews = new WP_Query( $args );
$count = 1;
$style="remaining-eight";
if ( $cnews->have_posts() ) :
while ( $cnews->have_posts() ) : $cnews->the_post();
if ( in_array( $count, range(1,2) ) )
$style="first-two";
?>
<div class="<?php echo $style; ?>" >
//post content in here
</div>
<?php
$count++;
endwhile;
wp_reset_postdata();
endif;
?>
</div>
Then you can you style based on the selectors first-two and remaining-eight.