你应该改变你的get_posts
到WP_Query
.
您正在进行大量查询,因为您正在运行setup_postdata
正在运行自己的一组查询,以从您通过的帖子中获取帖子数据get_posts
.
这可以通过使用WP_Query
相反
根据您的代码,当您更改为WP\\u 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>\'
?>
更新要将其简化为一个查询,可以执行以下操作:
<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>
然后您可以根据选择器进行样式设置
first-two 和
remaining-eight.