Site logo

Archived topic

Change posts per page function overwrites content template elements

6 replies · Started by Jesse on July 1, 2021

Viewing posts 1–7 of 7

I have a number of Custom Content Elements setup for the blog loop, first post, post navigation, categories, search results, etc.

When I add the code below to change the number of posts on the first page, all elements except for the blog loop and first post which has the blog loop as a parent stop working.

add_action( 'pre_get_posts', 'tu_change_posts_per_page', 1 );
function tu_change_posts_per_page( &$query ) {
    if ( ! is_main_query() ) {
        return;
    }

    if ( ! $query->is_paged ) {
        $query->set( 'posts_per_page', 10 );
    }
}

Hi there,

That's strange, so that filter prevents the Post Navigation block element from working (for example)?

Yes, that's right.

Okay, I've done some further testing on a new sandbox using Crypto from the Site Library.

When Code Snippets is set to "Run snippet everywhere" whatever number posts_per_page is set to is the number of elements that will be visible in the admin. I should have picked up on that one!

On the Blog page the post navigation stops working when posts_per_page is 5 or less.

On a single post when posts_per_page is 7 or less the default GP entry meta is shown instead of the custom one. When set to 8 the post navigation disappears completely.

Hi there,

You'll want to do this instead:

add_action( 'pre_get_posts', 'tu_change_posts_per_page', 1 );
function tu_change_posts_per_page( $query ) {
    if ( ! $query->is_main_query() ) {
        return;
    }

    if ( ! $query->is_paged ) {
        $query->set( 'posts_per_page', 4 );
    }
}

So this: $query->is_main_query()

Instead of this: is_main_query()

Using is_main_query() also applies to the Elements query, which is why you're seeing weirdness.

Hope this helps!

Thanks Tom, that got it sorted!

You're welcome :)

This archived topic is closed to new replies.