admin管理员组

文章数量:1391767

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);
}

本文标签: queryHow to change the amount of posts previewed on a page