Site logo

[Resolved] Change posts per page function overwrites content template elements

Home Forums Support [Resolved] Change posts per page function overwrites content template elements

Home Forums Support Change posts per page function overwrites content template elements

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #1841700
    Jesse

    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 );
        }
    }
    #1842778
    Tom
    Lead Developer
    Lead Developer

    Hi there,

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

    #1842785
    Jesse

    Yes, that’s right.

    #1843073
    Jesse

    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.

    #1843631
    Tom
    Lead Developer
    Lead Developer

    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!

    #1844942
    Jesse

    Thanks Tom, that got it sorted!

    #1845895
    Tom
    Lead Developer
    Lead Developer

    You’re welcome 🙂

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.