Handle pagination in wordpress custom php code

In case you are writing wordpress custom code and need to show lot of content, it may be a good idea to support pagination. The pagination url will look like /pagename/page/2, /pagename/page/3, etc. Here is wordpress code to read the page query variable:

$pageno = get_query_var('paged');

This will read the value in url after /page/. Now to display post and pages you can use get_posts api with query having offset and posts_per_page as shown below:

  $pageno = get_query_var('paged');
  // Add other conditions in $query as needed
  $query = array (
    'posts_per_page' => 10,
    'offset'  => 10*max($pageno-1, 0) ,
    'post_type'         => array('page', 'post'),
  $posts = get_posts($query);
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments