T
T
Thes2020-08-10 12:28:10
WordPress
Thes, 2020-08-10 12:28:10

How to fix custom pre_get_posts error on 404 error?

Hello!
I installed pure WP, created the "books" category and wrote a function that displays the required number of entries in this category:

add_action( 'pre_get_posts', 'books_posts_per_page' );
function books_posts_per_page( $query ) {
  if ( ! is_admin() && $query->is_main_query() && $query->is_category( 'books' ) ) {
    $query->set( 'posts_per_page', '1' );
  }
}

The function itself is working, it did not give errors in the process.
I started testing 404 errors (I just wrote a non-existing address like: site.ru/qwerty123) and then errors began to appear:
PHP Notice:  Trying to get property 'term_id' of non-object in \wp-includes\class-wp-query.php on line 3718
PHP Notice:  Trying to get property 'name' of non-object in \wp-includes\class-wp-query.php on line 3720
PHP Notice:  Trying to get property 'slug' of non-object in \wp-includes\class-wp-query.php on line 3722

Thanks to query-monitor, it turned out that this piece of code is to blame: " $query->is_category( 'books' ) ".
And even if you use standard methods:
if ( $query->is_main_query() && is_tag() ) {
$query->set( 'posts_per_page', '1' );
}

then no errors occur, but only when working with " $query->is_category() ".
I tried different methods: isset, empty, but it did not help, the only thing I found was that it was advised to process it through get_queried_object .

Can you please tell me how to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yarovikov, 2020-08-10
@Thes

https://wordpress.stackexchange.com/questions/1250...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question