it is working perfectly fine on category page but when I do similar
query on page, then it is not working
I can see why you used query_posts()
— your pagination function (kriesi_pagination()
) uses the main query (the global $wp_query
variable) to get the number of pages for your query, so you thought that altering the main query using query_posts()
would make the pagination work, right?
And basically, it would. But your query args is missing the paged
parameter — more details here.
Nonetheless, there’s no need to use query_posts()
because your custom pagination function actually allows passing a custom number of pages which is the first parameter for the function.
Therefore, just make a new instance of WP_Query
and pass the value of the instance’s $max_num_pages
property (i.e. WP_Query::$max_num_pages
) to the pagination function:
$query = new WP_Query( [
// .. your args here.
'paged' => max( 1, get_query_var( 'paged' ) ),
] );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
// .. your code.
endwhile;
endif;
kriesi_pagination( $query->max_num_pages );
wp_reset_postdata();
Additional Notes
-
Every time you make a custom/secondary instance of
WP_Query
and callsthe_post()
(orsetup_postdata()
), make sure to callwp_reset_postdata()
after your loop ends, so that the global$post
variable is restored back to the current post in the main query. Otherwise, for example, the next call tothe_title()
to display the title of the current post in the main query, you’d see the title of the last post in the above query and not the supposedly main query. -
You should also know that on category/archive/search/etc. “plural” pages, the
$wp_query->max_num_pages
value could be 2 or more depending on the total number of posts in the main query and the posts per page setting (which defaults to10
). So if by “my page”, you mean a Page (i.e. a post of thepage
type) which is a singular post, then the$wp_query->max_num_pages
would always be1
. And that might be the answer to “any idea why ?” in the question. -
If
kriesi_pagination()
still doesn’t work for you, you can try usingpaginate_links()
:echo paginate_links( [ 'total' => $query->max_num_pages, 'current' => max( 1, get_query_var( 'paged' ) ), ] );
And last but not least, avoid using query_posts()
as the WordPress core team suggested:
Its overly-simplistic approach to modifying the main query can be
problematic and should be avoided wherever possible. In most cases,
there are better, more performant options for modifying the main query
such as via
thepre_get_posts
action
withinWP_Query
.
Happy coding!