0

I'm trying to set posts_per_page depending on what category is being shown.

The following code works.

function category_posts_per_page( $query )
{

    if ( $query->is_main_query() && $query->is_category() && $query->is_category('books') ) {
        $query->set('posts_per_page', 2);
    }

}
add_action( 'pre_get_posts', 'category_posts_per_page' );

The problem:

I'm getting a php notice every 30 seconds in my debug log. No notices from visiting any posts, pages, categories or anything manually.

From debug.log:

[31-Oct-2018 10:18:46 UTC] PHP Notice:  Trying to get property 'term_id' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3502
[31-Oct-2018 10:18:46 UTC] PHP Notice:  Trying to get property 'name' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3504
[31-Oct-2018 10:18:46 UTC] PHP Notice:  Trying to get property 'slug' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3506

I've disabled all plugins, switched themes to a default one (and added the above code to functions.php).

How would I fix this? The code works and it's just a php notice, but it's a bit annoying... especially now in development and all notices are visible in debug.

1

is_category('category-name') won't work until after the query is run. If we check source code where those notices are generated, we can see that it's using get_queried_object, which gets populated with the results of the main query, and at the pre_get_posts stage will still be empty.

As an alternate, check the contents of $query->query_vars, which will be an array of query vars parsed from the requested URL.

  • Of course, get_queried_object should have told me that it was checking an already queried object, duh. :) Checking get_query_var('category_name')' for category name works great. Thank you for your help! – beholder Nov 1 '18 at 13:23
0

Maybe you should try this behavior happens only on frontend, with adding !is_admin like this. It is maybe due to the admin ajax heartbeat?

function category_posts_per_page( $query )
{

    if (!is_admin() && $query->is_main_query() && $query->is_category() && $query->is_category('books') ) {
        $query->set('posts_per_page', 2);

    }

}
add_action( 'pre_get_posts', 'category_posts_per_page' );
  • I did try that, but it didn't work. Thanks to @milo I managed to get it working. As he explained, is_category('category-name) checks AFTER the query is run, and I needed it to be done before. Here wordpress.stackexchange.com/a/318096/15809 – beholder Nov 1 '18 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.