HLJ 发布于
2019-04-29 17:07:16

wordpress主题首页与分类页的分页实现

制作wordpress主题时,首页、分类页、搜索页的分页效果是需要考量的,尤其是wordpress博客类主题,首页也是需要考虑在内的。如果分页设置不好,就有可能出现有些分页出现404的现象,我就曾经碰到过这样一个主题:首页分页效果正常,分类页后几页出现404现象。下面提供2种方案分页。

方案1:首页与分类页的分页放到1个勾子里。

在function.php文件里添加如下代码:
function custom_posts_per_page($query){
if(is_home()){
$query->set('posts_per_page',8);//首页每页显示8篇文章
}
if(is_search()){
$query->set('posts_per_page',-1);//搜索页显示所有匹配的文章,不分页
}
if(is_archive()){
$query->set('posts_per_page',25);//archive每页显示25篇文章
}
}
add_action('pre_get_posts','custom_posts_per_page');

方案2、首页与分类页分页分开放到2个不同的勾子里。

首页与分类文章每页数量分开来设置:
//限制首页文章每页数量
function custom_posts_per_page($query){
if(is_home()){
$query->set('posts_per_page',8);//首页每页显示8篇文章
}
}
add_action('pre_get_posts','custom_posts_per_page');
//限制分类页文章每页数量
function custom_posts_per_page2($query){
if(is_archive()){
$query->set('posts_per_page',25);//archive每页显示25篇文章
}//endif
}
add_action('pre_get_posts','custom_posts_per_page2');
这样,就不需要在循环中来设置每页显示文章数量,避免“最后一页404”的情况发生。
注:在列表循环 query_posts()中,不要再使用posts_per_page来限制数量,可以使用showposts 来限制。
文章来源:http://wanlimm.com/77201706085343.html 文章作者:高时银博客
最后生成于 2023-06-18 18:34:22
此内容有帮助 ?
0