通过WordPress的条件标签,可以任意扩展代码
- 时间:1年前
- 浏览:235次
wordpress/" target="_blank" style="margin: 0px; padding: 0px; color: rgb(61, 167, 13); text-decoration-line: none !important;">WordPress每页显示的文章数在后台阅读设置中指定,会应用到blog列表页(通常是首页)、搜索页、标签页、分类页以及时间索引页面,加入这些页面的结构不尽相同,例如有的显示标题和摘要,有的只显示标题,那么指定相同的页数就不适用于每个页面了。要根据页面类型指定每页显示文章数,需要写代码实现。
推荐的方法
修改每页显示的文章数也就是修改posts_per_page参数,将下面的代码放到functions.php中即可实现,代码来自WordPress Answers。
1 2 3 4 5 6 7 8 9 10 11 12 13 14function
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篇文章
}
//endif
}
//function
//this adds the function above to the 'pre_get_posts' action
add_action(
'pre_get_posts'
,
'custom_posts_per_page'
);
不推荐使用的方法
不推荐直接修改主题模板,例如在index.php主循环前用query_posts更改每页显示文章数目
1query_posts(
'posts_per_page=5'
);
缺点:
第一,增加查询次数
第二,灵活度不高,如果分类、标签有自己的模板,还需要到那些模板里重复query_posts的把戏。
第三,query_posts使用时需特别小心,如果忘记恢复全局变量,可能会出现莫名其妙的错误。
以上就是wordpress怎么手动自定义文章显示数量的详细内容!