How To Add Pagination To Your WordPress Theme

How To Add Pagination To Your WordPress Theme

If you are looking to add pagination support to your WordPress theme with cool numbers instead of the default next & previous post, you can do so using the famous PageNavi plugin, however, I much prefer adding pagination manually¬†to my themes so people don’t have to go searching for a plugin. It also helps keep the site faster without all the external scripts and CSS.

Luckily there is a great function in wordpress called “paginate_links” which was added in WordPress 2.1 and will allow you to create a paginated style navigation for any query on your site. Here is a quick tutorial for adding a simple page navigation to your theme that looks just like the pagination in my “Total WordPressTheme“.

Pagination PHP

Simply add the following code at the end of your functions.php file (or whatever file in your theme where you want to keep it).

// Numbered Pagination
if ( !function_exists( 'wpex_pagination' ) ) {
	
	function wpex_pagination() {
		
		$prev_arrow = is_rtl() ? '→' : '←';
		$next_arrow = is_rtl() ? '←' : '→';
		
		global $wp_query;
		$total = $wp_query->max_num_pages;
		$big = 999999999; // need an unlikely integer
		if( $total > 1 )  {
			 if( !$current_page = get_query_var('paged') )
				 $current_page = 1;
			 if( get_option('permalink_structure') ) {
				 $format = 'page/%#%/';
			 } else {
				 $format = '&paged=%#%';
			 }
			echo paginate_links(array(
				'base'			=> str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
				'format'		=> $format,
				'current'		=> max( 1, get_query_var('paged') ),
				'total' 		=> $total,
				'mid_size'		=> 3,
				'type' 			=> 'list',
				'prev_text'		=> $prev_arrow,
				'next_text'		=> $next_arrow,
			 ) );
		}
	}
	
}

View All Parameters

Pagination CSS

Copy the following CSS and paste into your style.css file.

ul.page-numbers {
    list-style: none;
    margin: 0;
}

.page-numbers:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

ul.page-numbers li {
    display: block;
    float: left;
    margin: 0 4px 4px 0;
    text-align: center;
}

.page-numbers a,
.page-numbers span {
    line-height: 1.6em;
    display: block;
    padding: 0 6px;
    height: 18px;
    line-height: 18px;
    font-size: 12px;
    text-decoration: none;
    font-weight: 400;
    cursor: pointer;
    border: 1px solid #ddd;
    color: #888;
}

.page-numbers a span { padding: 0 }

.page-numbers a:hover,
.page-numbers.current,
.page-numbers.current:hover {
    color: #000;
    background: #f7f7f7;
    text-decoration: none;
}

.page-numbers:hover { text-decoration: none }

Adding The Pagination Function To Your Theme

To call back the pagination function it’s really simple. All you have to do is add the following code to your theme files where you want to show any sort of pagination. The most common are your index.php, home.php, category.php, tags.php, archive.php and search.php. But if you have any custom page templates with pagination support, you’ll want to add them here.

Replace default pagination with the following (normally located somewhere after endif ):

<?php wpex_pagination(); ?>

Custom Queries?

If you are creating a custom query using WP_Query this function won’t work unless you’ve defined your query in the $wp_query variable (which is bad, don’t do it). To fix it, I generally create new queries like the following:

$wpex_query = new WP_Query( $args );

This way I can alter the main pagination function to look for the variable when creating the pagination, example (editing the first snippet):

global $wp_query,$wpex_query;
if ( $wpex_query ) {
   $total = $wpex_query->max_num_pages;
} else {
   $total = $wp_query->max_num_pages;
}
AJ Clarke
Hey. My name is AJ and I am the boss around here. I own and operate WPExplorer. A website dedicated to everything I love about WordPress.
AJ Clarke
This article has 38 comments
  1. Anthony says:

    So I figured out how to navigate around the Pytheas theme. Suuuuper cool theme btw! I was just thinking it would awesome if one could paginate the home (portfolio) page. If I set my posts to like say a hundred, then it would automatically create an additional page. Thumbs up guys!!! Good work!!!

    1. Kyla says:

      We’re glad you like the theme! It’s definitely possible but it would have to reload the page… the best option would be an ajax load more option.

      Admin
    2. anam says:

      firstly i enter the above mentioned code at the end of the functions.php and press the upgrade button then i found this error
      Parse error: syntax error, unexpected ‘clear’ (T_STRING), expecting ‘,’ or ‘;’ in /home4/raza/public_html/easytipstricks/wp-content/themes/goodnews47/functions.php on line 22
      wtf is this?

      1. AJ Clarke says:

        This was a very old post, I’ve completely updated it and made it better ;)

        Admin
    1. AJ Clarke says:

      The GoPress theme has pagination built-in. And actually since this post was created a long time ago…there is now a better way using the core function paginate_links(), learn more on the Codex.

      ps: Have you seen the updated GoPress Theme?

      Admin
  2. Kristoff says:

    Thank you so much, every other solution I had found was broken. This was the one that worked perfectly.

    1. AJ Clarke says:

      This is nice Jonathan, but you can tweak it a bit. Because you are passing the variable into the function no need to call it globally. There isn’t also a need for a multi-level variable. You could just do it like this:

      function wpex_pagination( $the_query = NULL ) {
        global $wp_query;
        $the_query = $the_query ? $the_query : $wp_query;
        $total = $the_query->max_num_pages;
      

      And of course your function would be like this…

      wpex_pagination( $your_custom_query_var );
      
      Admin
      1. Jonathan Lafleur says:

        You are totally right ! I was looking really too far ! Thank’s

  3. ken says:

    Hello.
    I would like to add pagination to three pages in my wordpress website I’m building. I’m new to wordpress and actually learning a lot. I do appreciate the codes given on this site. I downloaded the wp-pagenavi plugin, however I did not activate it yet. Can someone give me step by step instruction on where to insert the codes? ( Jupiter wordpress)
    I was informed to go into the FTP, I can give you access if needed

    1. AJ Clarke says:

      99% of themes include pagination by default, are you sure your theme doesn’t already have pagination built-in?

      If you do want someone to assist with the code I would recommend Envato Studio.

      Admin
  4. Filip van Hoeckel says:

    Works great, although your code does need ; after &larr and &rarr, otherwise it would just output the string. Cheers.

  5. pupuse says:

    Hi AJ Clarke,

    Thank you for this code! I probably do something wrong, but when I click the second page, it does show the same posts as on the first page. i did read some articles bout query_posts, but I do not think I use that. Do you maybe have any idea why it doesn’t work correctly and where I have to look?

    1. AJ Clarke says:

      If you can share your loop with me, I’ll help out. Link to a gist or pastebin to share the code, please don’t paste it in the comments it may get messed up.

      Admin
  6. pupuse says:

    Hi AJ Clarke,

    Thank you very much for the code. But I only get the same posts on page 1 as I get on page two. Did I do something wrong?

    1. AJ Clarke says:

      That depends on your loop itself. For example the standard loop is defined at Settings->Reading, while a custom loop would be the posts_per_page parameter.

      Admin
      1. pupuse says:

        In my settings -> reading -> Blog pages show at most is 8. At this moment I have 10 posts, so two of them should show up at page two. Before there no pagination, so I only used your code and placed this in functions.php, index.php and slyles.css of my theme. I searched in these files for ‘posts_per_page” but did not find a result. The page: http://www.hotelsandproperties.com/nl/nieuws/

        I hope you can help.

        1. AJ Clarke says:

          Looks like pagination is working now ;) I see 8 posts per page and 2 pages.

          Admin
          1. pupuse says:

            Unfortunately when you click on the second page, you will see the same posts as on the first page.

            1. AJ Clarke says:

              If this is on the homepage, then the issue is probably that your custom query is conflicting with the main query, you’ll probably have to use $wp_query – $wp_query = new WP_Query( $args ) – and then reset it after the loop. Pagination with custom queries on the homepage is tricky but if you google it you’ll find some useful info.

              Admin
  7. Geraldi says:

    I get the same posts on page 2,3,4… as I get on page 1.

    I am using this code in my custom blog page template [edited]

    plz help me

    1. AJ Clarke says:

      Like I said pagination is very tricky on the homepage with a custom query, you’ll probably need to change ‘wpex_query’ to ‘wp_query’ then add some extra arguments to reset pagination, example:

      global $post, $paged, $more;
      $more = 0;
      if ( get_query_var( 'paged' ) ) {
      	$paged = get_query_var( 'paged' );
      } else if ( get_query_var( 'page' ) ) {
      	$paged = get_query_var( 'page' );
      } else {
      	$paged = 1;
      }
      // Query posts
      $wp_query = new WP_Query(
      	array(
      		'post_type'		=> 'post',
      		'paged'			=> $paged,
      	)
      );
      
      Admin
  8. Sarkari naukri says:

    Hi i am using Open estate wordpress theme but there theme pagination is not working please help me how to use pagination in that theme.

    1. AJ Clarke says:

      That is a premium theme, you should contact the developer for support and they should be able to help you.

      Admin
  9. jaime // the briny says:

    Hi there, AJ. Your tutorial was a great help to me; I managed to get the numeric pagination in place on my blog. Thank you!

    I just have one problem and I’m wondering if you might know how to fix it. I’m using a Twenty Thirteen child theme which utilizes padding to specify the placement of the entry content. I’ve aligned the numeric pagination span to be more or less inline with my entry content, but on mobile devices this padding causes a problem–the rest of my site’s content is squished down to take up half of the horizontal space it should, and the pagination area is forced to the right. I’ve tried using margins and percentage values (instead of pixels), but it seems to cause the same issue.

    Would you be able to recommend another way I can align the pagination span with my entry content?

    Thank you!

    1. AJ Clarke says:

      There is a massive padding added to left side of “ul.page-numbers”, that’s what’s causing the issue.

      Admin
      1. jaime // the briny says:

        I’ve already identified that padding as the issue. What I was hoping to learn from you was a different approach for positioning the pagination span that wouldn’t cause problems (or that would be responsive) for mobile devices, while still keeping the placement I want for large screens. Any ideas you have would be greatly appreciated.

        1. AJ Clarke says:

          Sorry, I guess I didn’t really understand the issue then. All you need to do is move the code into the “entry-content” div (same div that the articles are in) because right now it spans 100% of the site.

          Admin
          1. jaime // the briny says:

            No worries, and thanks for looking at it again. Unfortunately, I tried to move the code into the entry content div previously, but it registers the pagination under every individual post (instead of just under the last one).

            I’ve also tried inspecting the element on my mobile device in attempts to specify 0 padding for the responsive/small-screen page, but haven’t had any luck there, either.

            1. AJ Clarke says:

              Things look a bit off in the coding of this theme…So I went to look in your child theme and it appears you may have copied/pasted the code from the main theme to the child theme? This is a big no no. Make sure your child theme only has your edits! Anyway looking at the theme locally…the coding in twenty-13 is very limiting and not very good to be honest. You’ll need to make your own tweaks to get it working nicely, there doesn’t seem to be any way to add it into a div and be done with it. I would find a better theme ;)

              Admin
  10. ddd says:

    done the same process as directed above… but the custom page pagination isn’t working at all.

    1. AJ Clarke says:

      Double check your code and the loop. Also, if you are adding pagination to the front-page via a custom Query you may need to add some extra code.

      Admin
  11. Amy says:

    Ding ding ding ding! Hours of research, trying 100 different things, and found the solution for using paginate_links within a wp_query right here. Thank you!

  12. Morshedul Arefin says:

    This is a great article and helped me a lot. Thank you very much Clarke to post this. Awesome job so far!!!

Leave a Reply