How to Fix Pagination on WordPress Custom Loops

So you have added a custom or secondary query to a template file and you get something strange on their pagination? Maybe this solution is solving your problem.

By default, in any given context, WordPress uses the main query to determine pagination. The main query object is stored in the $wp_query global, which is also used to output the main query loop:

[sourcecode]if ( have_posts() ) : while ( have_posts() ) : the_post();[/sourcecode]

When you use a custom query, you create an entirely separate query object:

[sourcecode]$custom_query = new WP_Query( $custom_query_args );[/sourcecode]

And that query is output via an entirely separate loop:

[sourcecode]if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :

But pagination template tags, including previous_posts_link(), next_posts_link(), posts_nav_link(), and paginate_links(), base their output on the main query object, $wp_query. That main query may or may not be paginated. If the current context is a custom page template, for example, the main $wp_query object will consist of only a single post – that of the ID of the page to which the custom page template is assigned.

If the current context is an archive index of some sort, the main $wp_query may consist of enough posts to cause pagination, which leads to the next part of the problem: for the main $wp_query object, WordPress will pass a paged parameter to the query, based on the paged URL query variable. When the query is fetched, that paged parameter will be used to determine which set of paginated posts to return. If a displayed pagination link is clicked, and the next page loaded, your custom query won’t have any way to know that the pagination has changed.

And your sollution is by passing Correct Paged Parameter to the Custom Query

Assuming that the custom query uses an args array:

$custom_query_args = array(
// Custom query parameters go here

You will need to pass the correct paged parameter to the array. You can do so by fetching the URL query variable used to determine the current page, via get_query_var():

get_query_var( ‘paged’ );

You can then append that paremeter to your custom query args 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. This is what you should have for a static front page

$custom_query_args[‘paged’] = get_query_var( ‘page’ )
? get_query_var( ‘page’ )
: 1;

Now, when the custom query is feteched, the correct set of paginated posts will be returned.

I hope it solve your  problem buddy 🙂