Consider this WordPress loop with a custom query and pagination. What will be the output on the second page?
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = [ 'post_type' => 'post', 'posts_per_page' => 3, 'paged' => $paged ]; $query = new WP_Query($args); if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); the_title('<h2>', '</h2>'); endwhile; echo paginate_links(['total' => $query->max_num_pages, 'current' => $paged]); endif; wp_reset_postdata(); ?>
Check how the 'paged' parameter controls which posts appear on each page.
The 'paged' variable is set from the query var and passed to WP_Query. This makes the query fetch posts for the current page. So on page 2, posts 4 to 6 show. Pagination links are generated using the total pages from the query.
Choose the correct way to pass the current page number to a custom WP_Query for pagination.
WordPress uses 'paged' query var for pagination, not 'page'.
The correct query var for pagination is 'paged'. Using get_query_var('paged') returns the current page number or empty if none. Using the null coalescing operator ?: sets it to 1 if empty. This is the standard way to get the current page for pagination.
Look at this code snippet. Why does pagination not work and always show the first page posts?
<?php $args = [ 'post_type' => 'post', 'posts_per_page' => 5 ]; $query = new WP_Query($args); if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); the_title('<h3>', '</h3>'); endwhile; echo paginate_links(['total' => $query->max_num_pages]); endif; wp_reset_postdata(); ?>
Check if the query knows which page to fetch.
Without the 'paged' argument, WP_Query always fetches the first page of posts. Pagination links may appear but clicking them won't change the posts shown because the query ignores the page number.
Assuming there are 12 published posts, what is the value of $query->max_num_pages after this query?
<?php $args = [ 'post_type' => 'post', 'posts_per_page' => 5, 'paged' => 1 ]; $query = new WP_Query($args); // What is $query->max_num_pages? ?>
Divide total posts by posts per page and round up.
There are 12 posts and 5 posts per page. 12 divided by 5 is 2.4, rounded up to 3 pages total. So max_num_pages is 3.
Why is it necessary to pass the 'paged' parameter to a custom WP_Query when implementing pagination?
Think about how WordPress knows which posts to show on page 2, 3, etc.
The 'paged' parameter tells WP_Query which page of posts to retrieve. If omitted, WP_Query defaults to page 1, so pagination links won't change the posts shown. This is essential for custom queries to support pagination.