I had the same problem and I noticed that in the 'posts_per_page = 6'
and 'Settings/Reading
on ‘options-reading’ WordPress argument, I was set to 10. When I put everything to the same value (6 in my case) everything started working again.
Johansson♦
15.1k10 gold badges39 silver badges77 bronze badges
answered Mar 10, 2018 at 14:56
7
In my case with custom links: /%category%/%postname%/
I had a problem with: /news/page/2/
And finally this works for me (add to functions.php):
function remove_page_from_query_string($query_string)
{
if ($query_string['name'] == 'page' && isset($query_string['page'])) {
unset($query_string['name']);
$query_string['paged'] = $query_string['page'];
}
return $query_string;
}
add_filter('request', 'remove_page_from_query_string');
answered Dec 6, 2018 at 15:48
3
Tried several hours, until I found a working solution in this article.
In your functions.php
file, add
/**
* Fix pagination on archive pages
* After adding a rewrite rule, go to Settings > Permalinks and click Save to flush the rules cache
*/
function my_pagination_rewrite() {
add_rewrite_rule('blog/page/?([0-9]{1,})/?$', 'index.php?category_name=blog&paged=$matches[1]', 'top');
}
add_action('init', 'my_pagination_rewrite');
Replace blog
with your category name in the code above.
After adding this code, make sure you go to Settings > Permalinks
and click Save
to flush the rules cache, or else the rule will not be applied.
Hope this helps!
answered Jul 17, 2018 at 11:11
kreguskregus
2512 silver badges4 bronze badges
2
I found changing the permalink structure work for me, look:
The permalink was like this in custom structure:
/index.php/%year%/%monthnum%/%day%/%postname%/
Then I changed it to: Day and name (just select the radio button) and it will look like this:
/%year%/%monthnum%/%day%/%postname%/
I tried this and it works!
Burgi
3731 silver badge15 bronze badges
answered Aug 16, 2017 at 2:36
1
my solution is in 3 step:
1- the first one : Installing this plugin : https://wordpress.org/plugins/category-pagination-fix/
2-then : mach your cod with this structure
<?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; ?>
<?php
$q=new wp_Query(
array(
"posts_per_page"=>10,
"post_type"=>"",
"meta_key"=>"",
"orderby"=>"meta_value_num",
"order"=>"asc",
"paged" => $paged,
)
);
while($q->have_posts())
{
$q->the_post();
?>
<li></li>
<?php
}
wp_reset_postdata();
?>
<div class="pagination">
<?php
global $q;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $q->max_num_pages
) );
?>
</div>
3-go in wordpress setting > reading > most number of posts per page of blog
then input number 1
fuxia♦
106k37 gold badges251 silver badges452 bronze badges
answered Jan 19, 2019 at 10:50
As others had mentioned. Make sure your ‘posts_per_page = 6’ is equal or less than the WordPress Settings > Reading > Blog pages show at most setting.
I ran into this issue recently and the issue was that I control the posts per page completely from the template file. If There are not enough posts for the final page it will 404.
for example. I have my posts per page set to 9, but I had 25 posts. page one and 2 would work but page 3 would 404. I set the WordPress setting to 1 and left my template file at 9 and it is now functioning as expected.
answered Jan 31, 2019 at 21:14
EspiEspi
215 bronze badges
In my case, using Divi and the PageNavi plugin, the reason I was getting the 404 was that the page template (archive in my case) was getting the paged
query parameter using get_query_var( 'paged' )
, instead all I had to do was use the global variable like below:
<?php
/*
Template Name: Archives
*/
get_header(); ?>
<?php
// $paged is a global variable provider by the theme?
global $paged;
$args = array(
'posts_per_page' => 4,
'post_type' => 'axis',
'paged' => $paged,
);
$myposts = new WP_Query($args);
?>
<div div style="width: 50%; margin: 0 auto;">
<?php while ( $myposts->have_posts() ) : $myposts->the_post(); ?>
<div class="media-body">
<?php the_content(); ?>
</div>
<?php endwhile; wp_reset_postdata(); ?>
<?php wp_pagenavi( array( 'query' => $myposts ) ); ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
This code corrected linked and resolved post-name/page/N
formatter posts.
The permalink setting is set to «Post Name» i.e. http://localhost/sample-post/
answered Jul 20, 2019 at 18:45
In my case I had this in a loop:
if (is_category()) $args['posts_per_page'] = 8;
And in Settings->Reading I had 10 posts per page for blog and syndication
I changed to 8 posts per page in Settings->Reading and now the 404 disappeared and everything seems to work.
I have no idea why but probably this could help someone in the future
answered Mar 17, 2020 at 22:24
NicolaNicola
1177 bronze badges
Here’s a generalization of kregus’s answer that fixes all categories at once:
/**
* Fix pagination on archive pages
*/
function my_pagination_rewrite() {
$categories = '(' . implode('|', array_map(function($category){return $category->slug;}, get_categories())) . ')';
add_rewrite_rule($categories . '/page/?([0-9]{1,})/?$', 'index.php?category_name=$matches[1]&paged=$matches[2]', 'top');
}
add_action('init', 'my_pagination_rewrite');
answered Aug 22, 2020 at 4:10
For those who are using WooCommerce; I was looking for the same thing, and found out WooCommerce changes the posts_per_page
for product categories.
See: https://woocommerce.com/document/change-number-of-products-displayed-per-page/
By using the WooCommerce filter:
/**
* Change number of products that are displayed per page (shop page)
*/
add_filter( 'loop_shop_per_page', 'wc_update_loop_shop_per_page', 20 );
function wc_update_loop_shop_per_page( $cols ) {
// $cols contains the current number of products per page based on the value stored on Options –> Reading
// Return the number of products you wanna show per page.
$cols = 9;
return $cols;
}
In my case I changed the $cols
to 12 and then the pagination was working fine again.
answered Apr 20 at 13:53
Loosie94Loosie94
2112 silver badges10 bronze badges
I had this issue too, tried all of the other solutions on this page, nothing helped. In my case, this was caused by having the ‘Category base’ the same as my blog page permalink.
E.g. my blog page permalink was ‘articles’ and I had set the ‘Category base’ (in Settings > Permalinks) set to ‘articles’ too. Changing the ‘Category base’ to something else, fixed the 404s.
answered May 19 at 13:18
I’m getting the error 404 when I head back to the url with /page/2/...
. So I go to my WordPress 404 page and add this javascript on the top of the error page:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var getreurl = window.location.href;
if(getreurl != ""){
var res = getreurl.split("/?");
if(res[1] != ""){
var resd = "http://www.yourwebsite.com/list/?"+res[1];
window.location = resd;
}
}
</script>
When I head back to the 404 page it carries the URL, I parse the URL and get URL string that I need and rebuild a new link then redirect on the new rebuilt link.
Burgi
3731 silver badge15 bronze badges
answered Jan 19, 2017 at 7:28
1
Found the solution!
Installing this plugin solved the problem:
https://wordpress.org/plugins/category-pagination-fix/
I also had to make changes in Settings > Reading to show less than 10 posts per page (I’m showing 6 posts per page now, but anything below 10 should work).
Hope it works for you all.
answered Nov 27, 2015 at 19:53
2
Разрабатывая тему для сайта столкнулся со следующей проблемой – 404 ошибка при использовании пагинации в файле category.php с помощью функции the_posts_pagination()
Задавшись вопросом почему не работает функция the_posts_pagination () стал искать ответ в рунете. Как ни странно конкретного ответа на этот вопрос найти не получилось, но я понял, что не первый, кто с ней столкнулся и вырисовывалась следующая картинка.
Итак, что же происходит?
Данная ситуация возникает тогда, когда в настройках сайта, в разделе “Настройки постоянных ссылок” выбран произвольный формат:
/%category%/%postname%/
И вроде бы сначала, все хорошо, но когда мы переходим на вторую страницу WordPress отправляет нас на страницу похожую на эту:
www.your_site.ru/your_taxonomy/page/2
В итоге добавленные /page/2 конфликтуют с настройкой постоянных ссылок, что и приводит к 404-ой ошибке.
Какое решение?
Нам нужно добиться двух вещей, чтобы решить эту проблему.
Во-первых, нам нужно, чтобы удалить часть URL из-за которого происходит ошибка, прежде чем WordPress пытается обработать запрашиваемый адрес. Для этого добавим следующий код в файл functions.php:
function codernote_request($query_string ) { if ( isset( $query_string['page'] ) ) { if ( ''!=$query_string['page'] ) { if ( isset( $query_string['name'] ) ) { unset( $query_string['name'] ); } } } return $query_string; } add_filter('request', 'codernote_request');
Во-вторых, реализуем механизм получения номера запрашиваемой страницы из URL и добавим его в запрос WordPress в требуемом формате. Опять же в файл functions.php добавим код:
add_action('pre_get_posts', 'codernote_pre_get_posts'); function codernote_pre_get_posts( $query ) { if ( $query->is_main_query() && !$query->is_feed() && !is_admin() ) { $query->set( 'paged', str_replace( '/', '', get_query_var( 'page' ) ) ); } }
Что делать если нет доступа к function.php или не знаю что это?!
В этом случае вы можете использовать плагин Category pagination fix Но лично я не очень люблю использовать плагины там, где можно что то сделать самому =)
I had the same problem and I noticed that in the 'posts_per_page = 6'
and 'Settings/Reading
on ‘options-reading’ WordPress argument, I was set to 10. When I put everything to the same value (6 in my case) everything started working again.
Johansson♦
15.1k10 gold badges39 silver badges77 bronze badges
answered Mar 10, 2018 at 14:56
7
In my case with custom links: /%category%/%postname%/
I had a problem with: /news/page/2/
And finally this works for me (add to functions.php):
function remove_page_from_query_string($query_string)
{
if ($query_string['name'] == 'page' && isset($query_string['page'])) {
unset($query_string['name']);
$query_string['paged'] = $query_string['page'];
}
return $query_string;
}
add_filter('request', 'remove_page_from_query_string');
answered Dec 6, 2018 at 15:48
3
Tried several hours, until I found a working solution in this article.
In your functions.php
file, add
/**
* Fix pagination on archive pages
* After adding a rewrite rule, go to Settings > Permalinks and click Save to flush the rules cache
*/
function my_pagination_rewrite() {
add_rewrite_rule('blog/page/?([0-9]{1,})/?$', 'index.php?category_name=blog&paged=$matches[1]', 'top');
}
add_action('init', 'my_pagination_rewrite');
Replace blog
with your category name in the code above.
After adding this code, make sure you go to Settings > Permalinks
and click Save
to flush the rules cache, or else the rule will not be applied.
Hope this helps!
answered Jul 17, 2018 at 11:11
kreguskregus
2512 silver badges4 bronze badges
2
I found changing the permalink structure work for me, look:
The permalink was like this in custom structure:
/index.php/%year%/%monthnum%/%day%/%postname%/
Then I changed it to: Day and name (just select the radio button) and it will look like this:
/%year%/%monthnum%/%day%/%postname%/
I tried this and it works!
Burgi
3731 silver badge15 bronze badges
answered Aug 16, 2017 at 2:36
1
my solution is in 3 step:
1- the first one : Installing this plugin : https://wordpress.org/plugins/category-pagination-fix/
2-then : mach your cod with this structure
<?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; ?>
<?php
$q=new wp_Query(
array(
"posts_per_page"=>10,
"post_type"=>"",
"meta_key"=>"",
"orderby"=>"meta_value_num",
"order"=>"asc",
"paged" => $paged,
)
);
while($q->have_posts())
{
$q->the_post();
?>
<li></li>
<?php
}
wp_reset_postdata();
?>
<div class="pagination">
<?php
global $q;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $q->max_num_pages
) );
?>
</div>
3-go in wordpress setting > reading > most number of posts per page of blog
then input number 1
fuxia♦
106k37 gold badges251 silver badges452 bronze badges
answered Jan 19, 2019 at 10:50
As others had mentioned. Make sure your ‘posts_per_page = 6’ is equal or less than the WordPress Settings > Reading > Blog pages show at most setting.
I ran into this issue recently and the issue was that I control the posts per page completely from the template file. If There are not enough posts for the final page it will 404.
for example. I have my posts per page set to 9, but I had 25 posts. page one and 2 would work but page 3 would 404. I set the WordPress setting to 1 and left my template file at 9 and it is now functioning as expected.
answered Jan 31, 2019 at 21:14
EspiEspi
215 bronze badges
In my case, using Divi and the PageNavi plugin, the reason I was getting the 404 was that the page template (archive in my case) was getting the paged
query parameter using get_query_var( 'paged' )
, instead all I had to do was use the global variable like below:
<?php
/*
Template Name: Archives
*/
get_header(); ?>
<?php
// $paged is a global variable provider by the theme?
global $paged;
$args = array(
'posts_per_page' => 4,
'post_type' => 'axis',
'paged' => $paged,
);
$myposts = new WP_Query($args);
?>
<div div style="width: 50%; margin: 0 auto;">
<?php while ( $myposts->have_posts() ) : $myposts->the_post(); ?>
<div class="media-body">
<?php the_content(); ?>
</div>
<?php endwhile; wp_reset_postdata(); ?>
<?php wp_pagenavi( array( 'query' => $myposts ) ); ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
This code corrected linked and resolved post-name/page/N
formatter posts.
The permalink setting is set to «Post Name» i.e. http://localhost/sample-post/
answered Jul 20, 2019 at 18:45
In my case I had this in a loop:
if (is_category()) $args['posts_per_page'] = 8;
And in Settings->Reading I had 10 posts per page for blog and syndication
I changed to 8 posts per page in Settings->Reading and now the 404 disappeared and everything seems to work.
I have no idea why but probably this could help someone in the future
answered Mar 17, 2020 at 22:24
NicolaNicola
1177 bronze badges
Here’s a generalization of kregus’s answer that fixes all categories at once:
/**
* Fix pagination on archive pages
*/
function my_pagination_rewrite() {
$categories = '(' . implode('|', array_map(function($category){return $category->slug;}, get_categories())) . ')';
add_rewrite_rule($categories . '/page/?([0-9]{1,})/?$', 'index.php?category_name=$matches[1]&paged=$matches[2]', 'top');
}
add_action('init', 'my_pagination_rewrite');
answered Aug 22, 2020 at 4:10
For those who are using WooCommerce; I was looking for the same thing, and found out WooCommerce changes the posts_per_page
for product categories.
See: https://woocommerce.com/document/change-number-of-products-displayed-per-page/
By using the WooCommerce filter:
/**
* Change number of products that are displayed per page (shop page)
*/
add_filter( 'loop_shop_per_page', 'wc_update_loop_shop_per_page', 20 );
function wc_update_loop_shop_per_page( $cols ) {
// $cols contains the current number of products per page based on the value stored on Options –> Reading
// Return the number of products you wanna show per page.
$cols = 9;
return $cols;
}
In my case I changed the $cols
to 12 and then the pagination was working fine again.
answered Apr 20 at 13:53
Loosie94Loosie94
2112 silver badges10 bronze badges
I had this issue too, tried all of the other solutions on this page, nothing helped. In my case, this was caused by having the ‘Category base’ the same as my blog page permalink.
E.g. my blog page permalink was ‘articles’ and I had set the ‘Category base’ (in Settings > Permalinks) set to ‘articles’ too. Changing the ‘Category base’ to something else, fixed the 404s.
answered May 19 at 13:18
I’m getting the error 404 when I head back to the url with /page/2/...
. So I go to my WordPress 404 page and add this javascript on the top of the error page:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var getreurl = window.location.href;
if(getreurl != ""){
var res = getreurl.split("/?");
if(res[1] != ""){
var resd = "http://www.yourwebsite.com/list/?"+res[1];
window.location = resd;
}
}
</script>
When I head back to the 404 page it carries the URL, I parse the URL and get URL string that I need and rebuild a new link then redirect on the new rebuilt link.
Burgi
3731 silver badge15 bronze badges
answered Jan 19, 2017 at 7:28
1
Found the solution!
Installing this plugin solved the problem:
https://wordpress.org/plugins/category-pagination-fix/
I also had to make changes in Settings > Reading to show less than 10 posts per page (I’m showing 6 posts per page now, but anything below 10 should work).
Hope it works for you all.
answered Nov 27, 2015 at 19:53
2
If you use customized permalinks such as /%category%/%postname%/
you may receive a 404 error when trying to access your WordPress page, https://yoursite.com/page/2/
and so on.
This is an error that has been occurring since WordPress 2.7, and even today it happens more than reasonable when accessing the web page, no matter what theme you have.
This happens more than I thought but, like everything in WordPress, it has one or several possible solutions.
Change the permalinks
The first solution is obvious, to change the structure of permalinks.
Go to your WordPress desktop and under Settings > Permalinks
, change the current custom structure to “postname
“.
I understand that you may not always be able to make this change, mainly due to SEO issues, but I recommend you at least to try it.
Change the structure as I say and try to see if the pagination works. Then, if you can make the perfect permalink change, you can keep this structure and make the 301 or regex redirects that are necessary to not lose positioning.
Delete .htaccess
Also, on occasion, permanent links may not be properly written from the server. To check this, nothing is easier than deleting the current .htaccess file (it will be in the root folder where WordPress is installed).
Then go to the WordPress desktop, to Settings > Permalinks
, and save changes without touching any settings.
Use a function that corrects the paging error
If none of the above works, or you can’t apply it, the following code will fix the problem in 99% of the cases.
function wphelp_custom_pre_get_posts( $query ) {
if( $query->is_main_query() && !$query->is_feed() && !is_admin() && is_category()) {
$query->set( 'paged', str_replace( '/', '', get_query_var( 'page' ) ) ); } }
add_action('pre_get_posts','wphelp_custom_pre_get_posts');
function wphelp_custom_request($query_string ) {
if( isset( $query_string['page'] ) ) {
if( ''!=$query_string['page'] ) {
if( isset( $query_string['name'] ) ) { unset( $query_string['name'] ); } } } return $query_string; }
add_filter('request', 'wphelp_custom_request');
Code language: PHP (php)
Add the code to the end of the functions.php file of the active theme or to your miscellaneous customizations plugin, save the changes and it will almost certainly be fixed.
Read this post in Spanish: Cómo arreglar el error 404 en la paginación con enlaces permanentes personalizados
Im have a loop with wp_query with the following code:
<?php
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query("showposts=2&paged=$paged");
?>
<?php if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<?php the_title() ?>
<?php endwhile; ?>
<?php else: ?>
<article>
<h2><?php _e( 'Sorry, nothing to display.', 'theme' ); ?></h2>
</article>
<?php endif; my_pagination(); wp_reset_query()?>
with standard pagination :
<?php
function my_pagination()
{
global $wp_query;
$big = 999999999;
echo paginate_links(array(
'base' => str_replace($big, '%#%', get_pagenum_link($big)),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'prev_text' => __('<i class="fa fa-chevron-left"></i>'),
'next_text' => __('<i class="fa fa-chevron-right"></i>'),
'total' => $wp_query->max_num_pages,
));
}
?>
The pagination is showing correctly on the page, but whenever I click on the pagination link it takes me to the error page.
Tried everything now and have no idea what can be the reason for it.
Amy help much apprecieated