我在div中添加了每2个帖子,但我也希望在不同的div中获得第一篇帖子,如下所示:
<div class="first">
<h2>Post title</h2>
</div>
<div>
<h2>Post title</h2>
<h2>Post title</h2>
</div>
<div>
<h2>Post title</h2>
<h2>Post title</h2>
</div>
这是我的代码:
<?php
$count = 5;
$args = array(
'cat' => $mag_cat,
'post_type' => 'post',
'post__not_in' => get_option( 'sticky_posts' ),
'posts_per_page' => $count
);
$posts = get_posts( $args ); ?>
<?php foreach ( array_chunk ( $posts, 2, true ) as $posts) :
if ( $posts == 0 ) {
echo '<div class="first">';
} else {
echo '<div>';
}
foreach( $posts as $post ) : setup_postdata($post); ?>
<h2>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h2>
<?php endforeach; ?>
</div>
班级。首先似乎不打印,我做错了什么?
答案 0 :(得分:0)
array_chunk
不允许您使第一个块比其余块小。除此之外,我不清楚为什么要将值(数组)与整数进行比较。
使用array_merge和array_slice实现所需内容的低效方法:
foreach(array_merge([[$posts[0]]], array_chunk(array_slice($posts, 1), 2)) as $key => $value) {
if( $key === 0 ) {
echo '<div class="first">';
} else {
echo '<div>';
}
}
你可能会做得更好,但周围有适当的锅炉板:
if(have_posts()) {
the_post();
get_template_part('parts/post', 'first');
while(have_posts()) {
the_post();
get_template_part('parts/post');
if(have_posts()) {
the_post();
get_template_part('parts/post');
}
}
}
甚至
if(have_posts()) {
the_post();
get_template_part('parts/post', 'first');
while(have_posts()) {
for($i = 0; $i <= 1; $i++ ) {
if(have_posts()) {
the_post();
get_template_part('parts/post');
}
}
}
}