Yesterday, I talk about using WP_query or query_posts or get_posts and today I am going to explain the approach I use to have pagination using get_posts(). The other two methods take care of the pagination by them self by just passing the paged parameter along with the function call. But get_posts() is more of a raw function which I used to create paginated data on the basis of already existing pagination.
Here for the sake of explanation of approach, I am making the content
paginated where content is already paginated. We will make our extra
content work in order to the global $paged variable.
03 | $ppp = get_option( 'posts_per_page' ); |
08 | $custom_offset = $ppp *( $paged -1); |
14 | 'offset' => $custom_offset , |
19 | $posts_data = get_posts( $args ); |
21 | if ( count ( $posts_data ) > 0 ) { |
23 | foreach ( $posts_data as $post ) { |
24 | echo '<li><a href="' .get_permalink( $post ->ID ). '">' . $post ->post_title. '</a></li>' ; |
28 | echo '<p>No articles by this user</p>' ; |
This way the code make use of the global $paged
variable to see which page it is on, and set the value of offset
accordingly making the fetched content using get_posts itself paginated.
On Page 1, the offset will be zero, it will fetch the posts limited by
the posts per page value and on Page 2, the offset will be calculated to
leave the posts already shown on previous page and query further posts
limited by the posts per page value.
Got questions? Comment section is down below.
No comments:
Post a Comment