[Resolved] Need to add some custom code just before the pagination function

Home Forums Support [Resolved] Need to add some custom code just before the pagination function

Home Forums Support Need to add some custom code just before the pagination function

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #229946
    Paul

    I’m trying to achieve a specific layout which results in 7 posts on the home page, and 9 posts on subsequent pages – 2, 3, 4 etc. In addition to adding some code to functions.php I’ve been told I need to add the following code just before the pagination function:

    global $wp_query;
    
    // Needed for first page only
    if ( ! $wp_query->is_paged ) {
        $all_posts_except_fp = ( $wp_query->found_posts - 7 ); // Get us the found posts except those on first page
        $wp_query->max_num_pages = ceil( $all_posts_except_fp / 9 ) + 1; // + 1 the first page we have containing 7 posts
    }

    Which file would I add this to, or will I need to create a custom home.php template in the child theme?

    This post provides more background info.

    My GeneratePress-based portfolio: http://www.pauldixonwebdesign.co.uk

    #229956
    Jean Paiva
    Developer

    Hey Paul based on the answer you need to do this:

    – This code you place at Inside Content Container Hook (GP Hooks)

    <?php global $wp_query;
    if ( ! $wp_query->is_paged ) {
        $all_posts_except_fp = ( $wp_query->found_posts - 7 ); // Get us the found posts except those on first page
        $wp_query->max_num_pages = ceil( $all_posts_except_fp / 9 ) + 1; // + 1 the first page we have containing 7 posts
    } ?>

    – And this goes to your functions.php

    add_action('pre_get_posts', 'myprefix_query_offset', 1 );
    function myprefix_query_offset(&$query) {
    
        if ( ! $query->is_home() ) {
            return;
        }
    
        $fp = 7;
        $ppp = 9;
    
        if ( $query->is_paged ) {
            $offset = $fp + ( ($query->query_vars['paged'] - 2) * $ppp );
            $query->set('offset', $offset );
            $query->set('posts_per_page', $ppp );
    
        } else {
            $query->set('posts_per_page', $fp );
        }
    
    }
    
    add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
    function myprefix_adjust_offset_pagination($found_posts, $query) {
    
        $fp = 7;
        $ppp = 9;
    
        if ( $query->is_home() ) {
            if ( $query->is_paged ) {
                return ( $found_posts + ( $ppp - $fp ) );
            }
        }
        return $found_posts;
    }

    It worked for me. Hope I’ve helped.

    #230137
    Paul

    Yep, that worked! Thanks Jean 🙂

    My GeneratePress-based portfolio: http://www.pauldixonwebdesign.co.uk

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