WordPress指定文章显示数量代码<?php query_posts(✀orderby=date&showposts=2&cat=✀.$catid); ?>哪错了?

2025-04-29 08:17:03
推荐回答(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篇文章
}//endif
}//function
//this adds the function above to the 'pre_get_posts' action
add_action('pre_get_posts','custom_posts_per_page');

说明:
用你问题上说的query_posts有以下缺点:

第一,增加查询次数
第二,灵活度不高,如果分类、标签有自己的模板,还需要到那些模板里重复query_posts的把戏。
第三,query_posts使用时需特别小心,如果忘记恢复全局变量,可能会出现莫名其妙的错误。

PS:上面的解答来自solagirl的一文 “WordPress根据页面类型指定每页显示的文章数”