最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

query - How to change the amount of posts previewed on a page?

programmeradmin2浏览0评论

I have tried this code, but it doesn't work.

function university_adjust_queries($query) {
    $query->set('post_per_page', '1');
}

add_action('pre_get_posts', 'university_adjust_queries');

I have tried this code, but it doesn't work.

function university_adjust_queries($query) {
    $query->set('post_per_page', '1');
}

add_action('pre_get_posts', 'university_adjust_queries');
Share Improve this question edited Feb 6, 2020 at 21:26 Hector 6821 gold badge7 silver badges18 bronze badges asked Feb 5, 2020 at 20:00 ChrisChris 1 1
  • You can change how many posts appear on archives in the settings in WP Admin, you don't need a filter for it – Tom J Nowell Commented Feb 5, 2020 at 21:26
Add a comment  | 

2 Answers 2

Reset to default 3

You're missing an s.

$query->set('posts_per_page', '1');

However - you probably don't want to do this for every query, since that affects everything - widgets, back end, everything. You should make it conditional. For example:

<?php
function university_adjust_queries($query) {
    // If this is the main query, not in wp-admin, and this is the homepage
    if($query->is_main_query() && !is_admin() && $query->is_home()) {
        $query->set('posts_per_page', '1');
    }
}
add_action('pre_get_posts', 'university_adjust_queries');
?>

This will make sure you're only affecting the main query (The Loop) on the homepage, and only on the front end. You can adjust the condition to target whichever spot you're wanting to affect.

function university_adjust_queries($query) {
  if (!is_admin() AND is_post_type_archive('event') AND $query->is_main_query()) {
        $query->set('posts_per_page', 1);
}
发布评论

评论列表(0)

  1. 暂无评论