Despite following exactly the example in the codex, the page I arrive at when clicking the pagination next
link (http://localhost:3000/my_project/news/page/2/) doesn't exist ("page not found").
Why?
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; echo 'paged = ' . $paged;
$regular_posts = new WP_Query('posts_per_page=3&paged=' . $paged);
while ($regular_posts->have_posts()): $regular_posts->the_post();
the_title();
endwhile;
echo get_next_posts_link('Older Entries', $regular_posts->max_num_pages);
This code is contained in my "home.php" template, managing the "News" page which I created in dashboard and set as "Posts page" in "Reading Settings".
Changing
$wp_query->posts_per_page
in the template with a new instance ofWP_Query
doesn't work because the requested page number has already been validated against$wp_query->max_num_pages
by WordPress before the template is executed. As the requested page is more than this value for the main query, the404.php
template is served instead, and your code in thehome.php
template isn't even executed.The trick is to get
$wp_query->max_num_pages
to match the true maximum number of pages by manipulating the main query to use your custom arguments, before the main query is performed.$wp_query->posts_per_page
and$wp_query->found_posts
will then match your results, resulting in a$wp_query->max_num_pages
that does too.The best way, in my opinion, is to edit the main query arguments before the main query gets its posts. For example, you could add the following to your theme's functions.php:
This will then mean a standard loop will work out the box too:
If you are only manipulating the number of posts per page, it may be better to change the default posts per page by going to
Options => Reading
in WordPress admin and settingBlog pages show at most
to 3 here instead.You can put this code in function.php file,
Also, put this code in your page or post template file,
This error usually occurs due to limits set on the number of posts to show on your templates. It's possible this is set to less than 4. So get to your WordPress dashboard and navigate to
Settings->Reading
. Look for Blog pages show at most and if the value is less than 4, increase it to the total number of posts to show on your template, plus the pagination link (in your case, this should be at least 4).A static homepage is slightly different from an archive, as it
page
parameter instead ofpaged
.The Codex Pagination page includes this code for static homepages, which will actually work in all cases (i.e. even archive pages) because its checking for both parameters:
But if you only need it to work on the homepage, Changing your code for the $paged variable to the following should work too: