custom query with pagination on home page
-
My home page need to retrieve some posts and break them into number of pages, so that I can load them using infinite scroll plugin. I have tested my query, it works as expected. however I can’t seems to get the pagination working.
For simplicity, I have removed some of the arguments from the query. Here goes:
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1; $argsSticky = array( 'posts_per_page' => 5, //'post_type' => array('post','video'), //'post__in' => $stickyPostIdArray, //'orderby' =>'post__in', 'paged' => $paged ); $temp_query = $wp_query; $stickyPosts = new WP_Query($argsSticky); $wp_query = NULL; $wp_query = $stickyPosts; if($stickyPosts->have_posts()) : while ($stickyPosts->have_posts()) : $stickyPosts->the_post(); //my loop block endwhile; wp_reset_postdata(); endif; <!-- pagination here --> <?php if ($stickyPosts->max_num_pages > 1) { ?> <nav class="prev-next-posts"> <div class="prev-posts-link"> <?php echo get_next_posts_link( 'Older Entries', $stickyPosts->max_num_pages ); ?> </div> <div class="next-posts-link"> <?php echo get_previous_posts_link( 'Newer Entries' ); ?> </div> </nav> <?php } ?> <?php // Reset main query object $wp_query = NULL; $wp_query = $temp_query; ?>
With the above code, if I load the home page, I can see the “Older Entries” link which links to the /page/2/, however, on page 2, there is no previous link, and the “Older Entries” is still links to the /page/2/.
If I manually update the url to load the pages after page 2. ie ‘dev.mydomain.com/page/3/” or ‘dev.mydomain.com/page/4/ the query works fine, the content loaded in the loop block are correct. However, ‘get_next_posts_link’ and ‘get_previous_posts_link’ does not seem to generate the correct page link. as if we are still on page 1.
I have read about the global $wp_query and overwrite it in the following post: “https://wordpress.stackexchange.com/questions/120407/how-to-fix-pagination-for-custom-loops”, and updated my code accordingly as above, but still no joy.
Could anyone tell me how to generate the correct pagination links. At least ‘next page’ and ‘previous page’ links. Any suggestion will be deeply appreciated. cheers.
- The topic ‘custom query with pagination on home page’ is closed to new replies.