Transient pagination not working properly

So I wrote the following to create a transient:

$wp_object_i_created = new WP_Query('cat=1');
set_transient('category_one_posts', $wp_object_i_created, 60*60*1);

Ok so then I decided “Ya know lets walk through this and spit out the posts.”

Read More

So I did the following:

if(false !== get_transient('category_one_posts')){
    $posts_inside = get_transient('category_one_posts');
    if($posts_inside->have_posts()){
        while($posts_inside->have_posts()){
            $posts_inside->the_post();
            // Display your posts in some maner.
        }
        echo get_next_posts_link('« Older Entries', $max_pages);
        echo get_previous_posts_link('Newer Entries »', $max_pages);
    }
 }

Now the pagination works – here’s the catch – It works in a really failed way. So I have it set to display 5 posts per page.

So if I go to my link: http://localhost/wordpress/?page_id=1667 I see my 5 posts and at the bottom my two links – one for older, one for newer. Woot. But if I click on the button “Older Entries” to go back, so my link now looks like: http://localhost/wordpress/?page_id=1667&paged=2 I see that were on page two, I can go one page forward and so on – BUT the posts are the same, they never updated.

Now regular queries done to get specific posts based on specific parameters, or even just the regular WordPress loop – their pagination all work as expected, you go to page two, you get a different set of posts then that on page one – woot! – we work.

But transient based pagination does not work.

Why?

Related posts

1 comment

  1. Short answer: You are making the same query no matter what page you are, but you’re expecting a different result.

    Long answer: The query should be different for second page, having paged=2, so your query (and transients) with pagination should look like this:

    $paged_var = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
    
    if ( get_transient( 'category_one_posts-' . $paged_var ) == false ) {
        $posts_inside = new WP_Query(
            array(
                 'cat' => 1,
                 'paged' => $paged_var
            )
        );
        set_transient( 'category_one_posts-' . $paged_var, $posts_inside, 60*60*1 );
    } else {
        $posts_inside = get_transient( 'category_one_posts-' . $paged_var );
    }
    
    if ( $posts_inside->have_posts() ) {
        while( $posts_inside->have_posts() ) {
            $posts_inside->the_post();
            // Display posts.
        }
    
        echo get_next_posts_link( __( 'Next', 'textdomain'), $posts_inside->max_num_pages );
        echo get_previous_posts_link( __( 'Previous', 'textdomain'), $posts_inside->max_num_pages );
    }
    

Comments are closed.