Site logo

Archived topic

Need to add some custom code just before the pagination function

2 replies · Started by Paul on September 27, 2016

Viewing posts 1–3 of 3

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.

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.

Yep, that worked! Thanks Jean :)

This archived topic is closed to new replies.