dtio35880438 2017-03-11 15:21
浏览 37

用array_chunk包装不同div中的第一篇文章

Im adding every 2 posts in a div, but i also want to get the first post in a different div like this:

<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>

Here is my code:

<?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>

The class .first does not seem to print, what I'm a doing wrong?

  • 写回答

1条回答 默认 最新

  • doujiao7325 2017-03-11 16:03
    关注

    array_chunk does not allow you to make the first chunk smaller than the rest. Besides this, it is unclear to me why you would compare the value (an array) against an integer.

    An inefficient way of accomplishing what you want is by using array_merge and 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>';
      }
    }
    

    You would probably be better off doing this though, with the appropriate boiler plate around it:

    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');
        }
      }
    }
    

    or even

    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');
          }
        }
      }
    }
    
    评论

报告相同问题?