0

I need paging on news archives page. Data is coming correctly if display all records on same page. But if i add paging code, then pagination values (such as 1,2,3,...16) coming correctly, but if i click on page 2 then it displays the same post title as on page 1.

    <h1 style="margin-left:10px;">News</h1>

    <ul class="years">
    <?php
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$all_posts = get_posts(array(
    'post_type' => 'news',
 'posts_per_page' => 20,
  'orderby' => 'date',
    'order' => 'DESC',
    'paged='. $paged,
));

    // this variable will contain all the posts in a associative array
    // with three levels, for every year, month and posts.

    $ordered_posts = array();

    foreach ($all_posts as $single) {

      $year  = mysql2date('Y', $single->post_date);
      $month = mysql2date('F', $single->post_date);

      // specifies the position of the current post
      $ordered_posts[$year][$month][] = $single;

    }

    // iterates the years
    foreach ($ordered_posts as $year => $months) { ?>
      <li>
        <h3><?php echo $year ?></h3>
        <ul class="months">
        <?php foreach ($months as $month => $posts ) { // iterates the moths ?>
          <li>
            <h3><?php printf("%s (%d)", $month, count($months[$month])) ?></h3>
            <ul class="posts">
              <?php foreach ($posts as $single ) { // iterates the posts ?>
                <li>
                  <?php echo mysql2date('F j', $single->post_date) ?> <a href="<?php echo get_permalink($single->ID); ?>"><?php echo get_the_title($single->ID); ?></a>  (<?php echo $single->comment_count ?>)</li>
                </li>

              <?php } // ends foreach $posts ?>
            </ul> <!-- ul.posts -->
          </li>
        <?php } // ends foreach for $months ?>
        </ul> <!-- ul.months -->
        <?php if(function_exists('wp_paginate')) {
        wp_paginate();
    }  ?>
      </li> <?php
    } // ends foreach for $ordered_posts
    ?>

    </ul><!-- ul.years -->

here is the screen shot:- enter image description here

Gaurav
  • 103
  • 1
  • 4

1 Answers1

0

Using your custom get_posts() you are ignoring the $paged var. In this way, you'll see always posts from the first page.

According the Codex Page if you would like to alter the main query before it is executed, you can hook into it using pre_get_posts.

function my_post_queries( $query ) {
  if (!is_admin() && $query->is_main_query()){
    $query->set('posts_per_page', 10);
    $query->set('post_type', array('news'));
    $query->set('orderby', 'date');
    $query->set('order', 'DESC');
  }
}
add_action( 'pre_get_posts', 'my_post_queries' );

In this way the $paged var is maintened from the main query.

You can also check if the main query is in a specific archive or whatever, in the hook function.