Last active
May 11, 2022 02:02
-
-
Save jonschr/bbba7d58c9aeb190df5e6c677620e5e0 to your computer and use it in GitHub Desktop.
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
| /** | |
| * 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