I am trying to implement PAGINATION or PAGING while retrieving all posts from database through custom query. I want to display 3 posts on every page. Logic wise it's working fine. Ex. If i click on First page it display 1,2,3 posts and if i click on second page it displays 4,5,6 post.
But problem is - 1. If i click on any page number link like 1 or 2 or 3 then everytime selected page should be active but in my program always first page number link is active.
If i click on Next, it always goes to second page. It should go to next page of current page.
Previous link doesn't display.
<?php $per_page = 3; $page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 0; if($page>0) $page = $page*$per_page-$per_page; $querystr = " SELECT $wpdb->posts.* FROM $wpdb->posts, $wpdb->postmeta WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = '_edit_last' AND $wpdb->postmeta.meta_value = '1' AND $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' AND $wpdb->posts.post_date < NOW() ORDER BY $wpdb->posts.post_date DESC LIMIT $per_page offset $page"; $pageposts = $wpdb->get_results($querystr, OBJECT); ?> <?php if ($pageposts): ?> <?php global $post;?> <?php foreach ($pageposts as $post): ?> <?php setup_postdata($post);?> <div class="post" id="post-<?php the_ID(); ?>"> <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small> <div class="entry"> <?php the_content('Read the rest of this entry »'); ?> </div> <p class="postmetadata">Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?></p>
PAGINATION
<?php
$querystr2 = "
SELECT count(*)
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->postmeta.meta_key = '_edit_last'
AND $wpdb->postmeta.meta_value = '1'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_date < NOW()
ORDER BY $wpdb->posts.post_date DESC
";
$totalPosts = $wpdb->get_var($querystr2);
echo paginate_links( array(
'base' => add_query_arg( 'cpage', '%#%' ),
'format' => '',
'prev_text' => __('Previous'),
'next_text' => __('Next'),
'total' => ceil($totalPosts / $per_page),
'current' => $page
));
?>
Can anyone try to solve this problem or find mistake in my code?