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♦
15k10 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
2412 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
3631 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♦
106k35 gold badges250 silver badges451 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
3631 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♦
15k10 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
2412 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
3631 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♦
106k35 gold badges250 silver badges451 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
3631 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
Since this has come up in two different forums lately, I am answering this.
If you use custom pagination, such as the one you’re using which appears to come from http://callmenick.com/post/custom-wordpress-loop-with-pagination but it happens with Genesis child themes too because the parent numbered pagination is what people what.
Why do you get a 404 page? The Custom pagination in the callmenick.com and Genesis (genesis_posts_nav) is for the main query and so if your pagination for your different query is under the posts per page in your reading settings (which is set for the main query), then you will get a 404 on page 2.
Every front end page request on a WordPress site produces a main
query. The template that WordPress decides to load is based on the
results of that main query (you can see the order that WordPress does
these things by looking at the Action Reference page). Despite the
fact that you never output the results of that query, it’s still run,
and in the case of paginated archives, this is an issue if you’re
trying to use that pagination for a different query.
— Milo https://wordpress.stackexchange.com/a/120963/64742
You don’t see this question a lot because many just build the pagination for that loop instead of re-using it from the functions.php file or a parent theme. You can learn that here: https://codex.wordpress.org/Function_Reference/paginate_links
Let’s start from the top and whenever you code, turn on debug in wp-config.php
A basic custom loop in my cpt archive.
archive-product.php
<?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$product_args = array(
'post_type' => 'product',
'posts_per_page' => 2, //the same as the parse_query filter in our functions.php file
'paged' => $paged,
'page' => $paged
);
$product_query = new WP_Query( $product_args ); ?>
<?php if ( $product_query->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $product_query->have_posts() ) : $product_query->the_post(); ?>
<article class="loop">
<h3><?php the_title(); ?></h3>
<div class="content">
<?php the_excerpt(); ?>
</div>
</article>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php
if (function_exists( 'custom_pagination' )) :
custom_pagination( $product_query->max_num_pages,"",$paged );
endif;
?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
In your functions.php file:
Learn about conditionals.
https://codex.wordpress.org/Conditional_Tags
https://codex.wordpress.org/Function_Reference/is_post_type_archive
/**
* Posts per page for CPT archive
* prevent 404 if posts per page on main query
* is greater than the posts per page for product cpt archive
*
* thanks to https://sridharkatakam.com/ for improved solution!
*/
function prefix_change_cpt_archive_per_page( $query ) {
//* for cpt or any post type main archive
if ( $query->is_main_query() && ! is_admin() && is_post_type_archive( 'product' ) ) {
$query->set( 'posts_per_page', '2' );
}
}
add_action( 'pre_get_posts', 'prefix_change_cpt_archive_per_page' );
/**
*
* Posts per page for category (test-category) under CPT archive
*
*/
function prefix_change_category_cpt_posts_per_page( $query ) {
if ( $query->is_main_query() && ! is_admin() && is_category( 'test-category' ) ) {
$query->set( 'post_type', array( 'product' ) );
$query->set( 'posts_per_page', '2' );
}
}
add_action( 'pre_get_posts', 'prefix_change_category_cpt_posts_per_page' );
/**
*
* custom numbered pagination
* @http://callmenick.com/post/custom-wordpress-loop-with-pagination
*
*/
function custom_pagination( $numpages = '', $pagerange = '', $paged='' ) {
if (empty($pagerange)) {
$pagerange = 2;
}
/**
* This first part of our function is a fallback
* for custom pagination inside a regular loop that
* uses the global $paged and global $wp_query variables.
*
* It's good because we can now override default pagination
* in our theme, and use this function in default queries
* and custom queries.
*/
global $paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
/**
* We construct the pagination arguments to enter into our paginate_links
* function.
*/
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";
echo $paginate_links;
echo "</nav>";
}
}
Итак, суть проблемы — при переходе на 2-3 и так далее страницы блога возникает 404 ошибка, если в пермалинках у нас установлены нестандартные ЧПУ.
Для начала на странице Permalink Settings просто нажмите Save Changes, это вызовет обновление файла .htaccess и обновление пермалинок на сайте, например, эту операцию нужно произвести после добавления кастомных типов записей, чтобы обновили (добавились) урлы для новых типов записей. Иногда эта операция помогает с 404 ошибками и сайт начинает работать как надо. Если 404 ошибка при пагинации осталась, двигаемся дальше.
Допустим, в Permalink Settings у нас стоят такие параметры
Custom Structure
/blog/%category%/%postname%/
А в Category base
В таком случае при переходе на страницу https://site.com/blog/nature/page/2/ получим 404 ошибку, что для меня было неожиданностью. Лечится данный баг добавлением в файл функций нижепредставленного кода
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');
После этого, пагинация по сайту работает без проблем.
Как заменить пагинацию WooCommerce на WP-PageNavi
Простой способ подключить вместо стандартной пагинации WooCommerce woocommerce_pagination пагинацию с помощью плагина WP-PageNavi. Устанавливаем и…
Ajax Load More
Repeater Templates index.php home.php
Не спешите обновлять CMS WordPress до версии 5.7 — обнаружен конфликт с Contact Form 7 версии 5.4
Итак, суть проблемы — на некоторых сайтах перестала работать форма обратной связи Contact Form 7…
Как сделать бекап и импортировать базу через SSH
Столкнулся с такой задачей, что нужно было импортировать базу через консоль по SSH, хотя обычно…