文章目录

最近在处理新站点陌泊小程序的时候,使用到了wordpress作为后台支持,在自定义主题时发现分页的时候总是返回404。数次度娘无果,最终寻求谷歌。

路途漫漫,但是功夫不负有心人,最终使用一个插件解决Category pagination fix

知其然,还要知其所以然。原文注释提到:the 'page' looks like a post name, not the keyword "page",也就是说wordpress会把分页路径中的page当成文章名来处理,自然就找不到了。

整个插件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* This plugin will fix the problem where next/previous of page number buttons are broken on list
* of posts in a category when the custom permalink string is:
* /%category%/%postname%/
* The problem is that with a url like this:
* /categoryname/page/2
* the 'page' looks like a post name, not the keyword "page"
*/
function remove_page_from_query_string($query_string)
{
if ($query_string['name'] == 'page' && isset($query_string['page'])) {
unset($query_string['name']);
// 'page' in the query_string looks like '/2', so i'm spliting it out
list($delim, $page_index) = split('/', $query_string['page']);
$query_string['paged'] = $page_index;
}
return $query_string;
}
// I will kill you if you remove this. I died two days for this line
add_filter('request', 'remove_page_from_query_string');

// following are code adapted from Custom Post Type Category Pagination Fix by jdantzer
function fix_category_pagination($qs){
if(isset($qs['category_name']) && isset($qs['paged'])){
$qs['post_type'] = get_post_types($args = array(
'public' => true,
'_builtin' => false
));
array_push($qs['post_type'],'post');
}
return $qs;
}
add_filter('request', 'fix_category_pagination');

另外,在用wp_query请求内容的时候,需要记得传递分页参数 paged

♦ 本文固定连接:http://gsgundam.com/2020-10-24-wordpress-category-pagination-fix/

♦ 转载请注明:GSGundam 2020年10月24日发布于 GSGUNDAM砍柴工