• I’ve managed to get and list my posts by year, but

    Code for listing posts by year:

    functions.php

    function posts_by_year() {
      // array to use for results
      $years = array();
    
      // get posts from WP
      $posts = get_posts(array(
        'numberposts' => -1,
        'orderby' => 'post_date',
        'order' => 'ASC',
        'post_type' => 'post',
        'post_status' => 'publish'
      ));
    
      // loop through posts, populating $years arrays
      foreach($posts as $post) {
        $years[date('Y', strtotime($post->post_date))][] = $post;
      }
    
      // reverse sort by year
      krsort($years);
    
      return $years;
    }

    template file

    <?php foreach(posts_by_year() as $year => $posts) : ?>
      <h2><?php echo $year; ?></h2>
    
      <ul>
        <?php foreach($posts as $post) : setup_postdata($post); ?>
          <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
          </li>
        <?php endforeach; ?>
      </ul>
    <?php endforeach; ?>

    What should I do next so that only 6 posts per page are shown?

    Anyone could give me a hint here?
    Thanks.

Viewing 6 replies - 1 through 6 (of 6 total)
  • I think you can use the posts_per_page parameter from query_posts in get_posts:

    $posts = get_posts(array(
        'numberposts' => -1,
        'orderby' => 'post_date',
        'order' => 'ASC',
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 6
      ));

    I’m not sure if you have to add something in your template for the pagination links or if WP does that on its own.

    Thread Starter diogobento

    (@diogobento)

    Thanks linux4me2,
    That was my first thought and I had already tried it, but something very strange happens: the latest post in repeated 6 times and no other posts are loaded!

    Give this a shot in your template:

    <?php foreach(posts_by_year() as $year => $post) : ?>
      <h2><?php echo $year; ?></h2>
    
      <ul>
        <?php setup_postdata($post); ?>
          <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
          </li>
      </ul>
    <?php endforeach; ?>

    Thread Starter diogobento

    (@diogobento)

    Now it shows 1 post per year!!

    Thread Starter diogobento

    (@diogobento)

    ??

    Thread Starter diogobento

    (@diogobento)

    Sorry, my mistake, it is working properly and the first solution solved the case. Well, sort of; now the pagination is missing. But that’s another topic.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘List posts by year, 6 per page.’ is closed to new replies.