0

I have seen examples where there is a fix number of posts to be queried; however, I cant find an example when using pagination.

I am trying to figure out how to use transients to cache a WP_Query with paging.

So far, I am showing 12 posts per page. When I load the next set of posts, the posts are the same first 12 posts. It is not getting the following posts.

  • Post your code please. – s_ha_dum May 20 '14 at 13:35
3

You need to set a unique transient key for each page of posts otherwise each page will output same posts.

Here is a example. Focus on get_transient & set_transient functions.

<?php

  $my_posts_query = get_transient( 'my_unique_transient_key_' . get_query_var( 'paged' ) );

  if( false === $my_posts_query ) {

    $args = array( 'post_type' => 'post', 'posts_per_page' => '12', 'paged' => $paged );
    $my_posts_query = new WP_Query( $args );

    set_transient( 'my_unique_transient_key_' . get_query_var( 'paged' ), $my_posts_query, 300 );
  }

  if ( $my_posts_query->have_posts() ) :

    while ( $my_posts_query->have_posts() ) :

      $my_posts_query->the_post();

      // Your loop

    endwhile;

    // This is responsible for 1, 2, 3 pagination links. You can easily change this to previous and nexys links.
    if ( $my_posts_query->max_num_pages > 1 ) :
      $big = 999999999;
      echo '<div class="pagination">';
      echo paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $my_posts_query->max_num_pages
      ) );
      echo '</div>';
    endif;

  endif;

  wp_reset_postdata();

?>
|improve this answer|||||
  • Thats awesome, i will test it when I get home. Thanks. – Gixty Jun 18 '14 at 13:14
  • Did it work? The code I posted. Let me know. – Robert hue Aug 27 '14 at 16:28
  • Hey Robert, I havent tested it yet but it looks like it works. I up voted it for now. Once I test it, I'll checked it as solved. – Gixty Sep 17 '14 at 10:40
  • Finally I got to test it. It's perfect! – Gixty Nov 27 '14 at 1:13
  • 1
    I found one issue. Transients for each page get different expiration times; thus, when one expires and the other hasnt, repeated posts appear. Could you please tell me a way to fix this? Thank you. – Gixty Nov 27 '14 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.