V
V
Vadim Sverdlik2020-05-24 19:29:39
WordPress
Vadim Sverdlik, 2020-05-24 19:29:39

Incorrectly fulfills pre get posts. How to decide?

I have this code in functiions.php , but 5 posts are displayed on the category pages and not 2, 5 is indicated in the admin panel. If you comment out

if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }


then on the page of the categories 2 entries are displayed as needed, but then on the main page it displays the wrong number. Tell me what could be the problem

function custom_posts_per_page( $query ) {

    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }


    if ( $query->is_search() ) {
        $query->set( 'posts_per_page', 8 );
    }

    if ( $query->is_category() ) {
        if ( wp_is_mobile() ) {
            $query->set( 'posts_per_page', 2 );
        } else {
            $query->set( 'posts_per_page', 2 );
        }

    }//endif

}//function

add_action( 'pre_get_posts', 'custom_posts_per_page' );

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WP Panda, 2020-05-24
@vadim_sverdlik

Leading question, did you make the topic yourself?

I
Igor, 2020-05-24
@loonny

So do it

If you comment out
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
then on the category page 2 entries are displayed as needed

Create an additional condition for the main page
if ( $query->is_home() ) {
  $query->set( 'posts_per_page', 5 );
}

but then on the main page it displays the wrong amount

The condition here is redundant.
if ( wp_is_mobile() ) {
  $query->set( 'posts_per_page', 2 );
} else {
  $query->set( 'posts_per_page', 2 );
}

and it can be replaced with Open the section "editing templates" or something similar. There you can immediately navigate to the documentation pages for the names of the functions.
$query->set( 'posts_per_page', 2 );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question