Saturday, August 4, 2012

Pagination approach using get_posts() in WordPress

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.

01<?php
02// Posts Per Page option
03$ppp = get_option('posts_per_page');
04 
05if (!is_paged()) {
06    $custom_offset = 0;
07} else {
08    $custom_offset = $ppp*($paged-1);
09}
10 
11// Lets suppose we are querying for posts of a certain author in a particular category
12$args = array(
13'numberposts' => $ppp,
14'offset' => $custom_offset,
15'category' => 7, // Category ID of category 'Articles'
16'author' => $author_id
17);
18 
19$posts_data = get_posts( $args );
20 
21if ( count( $posts_data ) > 0 ) {
22    echo '<ul>';
23    foreach ( $posts_data as $post ) {
24        echo '<li><a href="'.get_permalink( $post->ID ).'">'.$post->post_title.'</a></li>';
25    }
26    echo '</ul>';
27} else {
28    echo '<p>No articles by this user</p>';
29}
30?>
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