Created
March 6, 2021 13:33
-
-
Save Korveld/64b429c6caebb9287de2b688f5a2507f to your computer and use it in GitHub Desktop.
WP_Query with pagination and offset
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
| $current_page = get_query_var('paged'); | |
| $current_page = max( 1, $current_page ); | |
| $per_page = 12; | |
| $offset_start = 1; | |
| $offset = ( $current_page - 1 ) * $per_page + $offset_start; | |
| $post_list = new WP_Query(array( | |
| 'cat' => -15, | |
| 'posts_per_page' => $per_page, | |
| 'paged' => $current_page, | |
| 'offset' => $offset, // Starts with the second most recent post. | |
| 'orderby' => 'date', // Makes sure the posts are sorted by date. | |
| 'order' => 'DESC', // And that the most recent ones come first. | |
| )); | |
| // Manually count the number of pages, because we used a custom OFFSET (i.e. | |
| // other than 0), so we can't simply use $post_list->max_num_pages or even | |
| // $post_list->found_posts without extra work/calculation. | |
| $total_rows = max( 0, $post_list->found_posts - $offset_start ); | |
| $total_pages = ceil( $total_rows / $per_page ); | |
| if ( $post_list->have_posts() ): | |
| while ( $post_list->have_posts() ): | |
| $post_list->the_post(); | |
| // loop output here | |
| endwhile; | |
| echo paginate_links( array( | |
| 'total' => $total_pages, | |
| 'current' => $current_page, | |
| ) ); | |
| endif; | |
| wp_reset_postdata(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment