Last active
March 19, 2019 23:56
-
-
Save srikat/2abbf21854860f3699e51d5f174ec944 to your computer and use it in GitHub Desktop.
Changing the posts per page on first page without breaking pagination in WordPress. https://sridharkatakam.com/changing-posts-per-page-first-page-without-breaking-pagination-wordpress/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action( 'pre_get_posts', 'sk_query_offset', 1 ); | |
function sk_query_offset( &$query ) { | |
// Before anything else, make sure this is the right query... | |
if ( ! ( $query->is_home() || is_main_query() ) ) { | |
return; | |
} | |
// First, define your desired offset... | |
$offset = -1; | |
// Next, determine how many posts per page you want (we'll use WordPress's settings) | |
$ppp = get_option( 'posts_per_page' ); | |
// Next, detect and handle pagination... | |
if ( $query->is_paged ) { | |
// Manually determine page query offset (offset + current page (minus one) x posts per page) | |
$page_offset = $offset + ( ( $query->query_vars['paged']-1 ) * $ppp ); | |
// Apply adjust page offset | |
$query->set( 'offset', $page_offset ); | |
} | |
else { | |
// This is the first page. Set a different number for posts per page | |
$query->set( 'posts_per_page', $offset + $ppp ); | |
} | |
} | |
add_filter( 'found_posts', 'sk_adjust_offset_pagination', 1, 2 ); | |
function sk_adjust_offset_pagination( $found_posts, $query ) { | |
// Define our offset again... | |
$offset = -1; | |
// Ensure we're modifying the right query object... | |
if ( $query->is_home() && is_main_query() ) { | |
// Reduce WordPress's found_posts count by the offset... | |
return $found_posts - $offset; | |
} | |
return $found_posts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment