Skip to content

Instantly share code, notes, and snippets.

@jonschr
Last active May 11, 2022 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonschr/bbba7d58c9aeb190df5e6c677620e5e0 to your computer and use it in GitHub Desktop.
Save jonschr/bbba7d58c9aeb190df5e6c677620e5e0 to your computer and use it in GitHub Desktop.
/**
* Force first page of results in archives to an odd number, later pages to an even number
*/
add_action( 'pre_get_posts', 'elodin_change_posts_number_home_page_to_odd' );
function elodin_change_posts_number_home_page_to_odd( $query ) {
// only modify the query if it's the main query
if ( !is_admin() && $query->is_main_query() ) {
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$postsperpage = get_option( 'posts_per_page' );
// if we're on the first page and the number is even, add one to the number of posts to make it odd
if ( $paged === 1 && $postsperpage % 2 == 0 ) {
$postsperpage = $postsperpage + 1;
$query->set( 'posts_per_page', $postsperpage );
}
// if the number is even and we're past the first page, then offset by -1
if ( $paged > 1 && $postsperpage % 2 == 0 ) {
// the offset is the page times the number of pages minus the number on the current page plus one
$offset = $paged * $postsperpage - $postsperpage + 1;
$query->set( 'offset', $offset );
}
if ( $paged == 1 && $postsperpage % 2 != 0 ) {
// no adjustments needed
}
// if we're on the first page and the number is even, add one to the number of posts to make it odd
if ( $paged > 1 && $postsperpage % 2 != 0 ) {
$postsperpage = $postsperpage + 1;
$query->set( 'posts_per_page', $postsperpage );
// the offset is the page times the number of pages minus the number on the current page minus one
$offset = $paged * $postsperpage - $postsperpage - 1;
$query->set( 'offset', $offset );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment