Created
April 12, 2016 09:52
-
-
Save shizhua/c614d25f01809407ae863fb2636271b0 to your computer and use it in GitHub Desktop.
Fix pagination not working in custom query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Define custom query parameters | |
$custom_query_args = array( /* Parameters go here */ ); | |
// Get current page and append to custom query parameters array | |
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; | |
// If your page is a static front page, be sure to use page instead of paged as a static front page uses page and not paged | |
// https://codex.wordpress.org/Function_Reference/WP_Query#Pagination_Parameters | |
// $custom_query_args['paged'] = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1; | |
// Instantiate custom query | |
$custom_query = new WP_Query( $custom_query_args ); | |
// Pagination fix | |
$temp_query = $wp_query; // Backup the main query object | |
$wp_query = NULL; // Null the main query object | |
$wp_query = $custom_query; // Swap the custom query into the main query object | |
// Output custom query loop | |
if ( $custom_query->have_posts() ) : | |
while ( $custom_query->have_posts() ) : | |
$custom_query->the_post(); | |
// Loop output goes here | |
endwhile; | |
endif; | |
// Reset postdata | |
wp_reset_postdata(); | |
// Custom query loop pagination | |
previous_posts_link( 'Older Posts' ); | |
next_posts_link( 'Newer Posts', $custom_query->max_num_pages ); // By default the function will use max_num_pages for the main $wp_query object.So you will need to pass the max_num_pages of $custom_query object to the function | |
// Reset main query object | |
$wp_query = NULL; | |
$wp_query = $temp_query; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment