‘Roll Your Own’ Pagination

In order to provide pagination when query_posts() was used in a non-WP site, the technique shown here was used.

Standard pagination did not work because the ‘paged’ query variable was not set. Instead the ‘pg’ variable was used and added to the links created by previous/next_posts_link().

<?php

// 'Roll Your Own' pagination
// Only works on pretty permalinks!
function mam_set_page($link = '') {
   // Set the argument pg=nn on previous/next_posts_link()
   $new_link = $link;
   if (preg_match('#/page/(\d+)/#',$link,$matches)) {
      $new_link = preg_replace('#/page/(\d+)/#','/',$link);
      $new_link = mam_add_query_arg('pg',$matches[1],$new_link);
   } else {
      $new_link = mam_add_query_arg('pg',false,$new_link);
   }
   return $new_link;
}
 function mam_add_query_arg ($key,$value,$link) {
   // Adds the parameter $key=$value to $link, or replaces it if already there.
   // Necessary because add_query_arg fails on previous/next_posts_link.
   if (strpos($link,'href')) {
     $hrefpat = '/(href *= *([\"\']?)([^\"\' ]+)\2)/';
   } else {
     $hrefpat = '/(([\"\']?)(http([^\"\' ]+))\2)/';
   }
   if (preg_match($hrefpat,$link,$matches)) {
      $url = $matches[3];
      $newurl = add_query_arg($key,$value,$url);
      // echo '<p>OLDURL:' . htmlspecialchars($url) . '</p>';
      // echo '<p>NEWURL:' . htmlspecialchars($newurl) . '</p>';
      $link = str_replace($url,$newurl,$link);
   }

   return $link;
}

$paged = ( intval($_GET['pg'])) ? intval($_GET['pg']) : 1;
$args = array(
   'posts_per_page' => 10,
   'paged' => $paged,
   'ignore_sticky_posts' => 1
);
query_posts($args);
if (have_posts()) {
   while (have_posts()) {
      the_post();
      echo '<p>';the_title();echo '</p>';
   }
}
$next_link = mam_set_page(get_next_posts_link('&laquo; Older Entries'));
$prev_link = mam_set_page(get_previous_posts_link('Newer Entries &raquo;'));

?>
      <div class="navigation">
         <div class="alignleft"><?php echo $next_link; ?></div>
         <div class="alignright"><?php echo $prev_link; ?></div>
       </div>

Leave a Reply

Your email address will not be published. Required fields are marked *

*