Pagination in WordPress


<!--?php
global $wpdb;
if (isset($_GET['page'])) $page = $_GET['page']; else $page = 1;
$max_results = 25;//max size of data to show
$from = (($page * $max_results) - $max_results);
$sql = "SELECT company,phone FROM wp_csv "."ORDER BY id LIMIT $from, $max_results";
$array1 = $wpdb->get_results($sql);//wordpress database object sql query like mysql_query($sql)
foreach($array1 as $key)
{
	print "<tr class='bodytxt'><td class='brdcol' width='313' align='left' valign='top'>".$key->company."</td>"."<td class='brdcol' width='313' align='left' valign='top'>".$key->phone."</td></tr>";
}//$key->company is the object type field name of database
?>
<!--?php
// (1) get the total number of results for your query
// modify this to match the total results for the main query
/*$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num
FROM users"),0); */
$total_results = $wpdb->get_var('SELECT COUNT(*) FROM wp_csv');
// (2) Calculate total number of pages. Round up using ceil()
$total_pages = ceil($total_results / $max_results); 
if($total_results > $max_results)
{
  // (3) build Previous link
  if($page > 1)
  {
     $prev = ($page - 1);
     echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$prev\">&lt;&lt; Previous</a> ";
  } 
  // (4) display page numbers
  for($i = 1; $i <= $total_pages; $i++)
  {
     if($page == $i)
     {
        echo $i . " ";
     }
     else
     {
        echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i\">$i</a> ";
     }
  } 
  // (5) build Next Link
  if($page < $total_pages)
  {
       $next = ($page + 1);
       echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$next\">Next &gt;&gt;</a>";
  }
}
?>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s