改进上述答案:挂钩pre_get_posts
通过引用获取,因此它不需要global
呼叫或areturn
呼叫
add_action( \'pre_get_posts\', \'set_posts_per_page\' );
function set_posts_per_page( $query ) {
if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
$query->set( \'posts_per_page\', 3 );
}
elseif ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_archive() ) ) {
$query->set( \'posts_per_page\', 5 );
}
// Etc..
}