5 WordPress Pagination Code Snippets with Examples [Simple to Advanced]

pagination code in WordPress examples

If you are looking for the best pagination code in WordPress with specific examples, you will find the examples of pagination code snippets shared in this post to be very useful.

You can apply this pagination code in a WordPress theme or in a custom WordPress plugin that requires post-pagination.

Let me cut to the chase and share my favorite pagination code snippets:

#1) WordPress Loop with Simple Pagination Code

If you want to add pagination within the WordPress loop you can use the next and previous pagination code below:

<?php if ( have_posts() ) : ?>

<!-- Add the pagination functions here. -->

<!-- Start of the main loop. -->
<?php while ( have_posts() ) : the_post();  ?>

<!-- the rest of your theme's main loop -->

<?php endwhile; ?>
<!-- End of the main loop -->

<!-- Add the pagination functions here. -->

<div class="nav-previous alignleft"><?php previous_posts_link( 'Older posts' ); ?></div>
<div class="nav-next alignright"><?php next_posts_link( 'Newer posts' ); ?></div>

<?php else : ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

 

#2) WordPress Numeric Pagination

Another great WordPress pagination option is to use the numeric pagination which adds numbers to the posts and groups the posts based on a number.

For example, you can display 5 posts on a page. This is the pagination code in WordPress for numeric pagination:

<?php 

#STEP 1: Create the numeric WordPress pagination function 

function njengah_numeric_pagination() {
 
    if( is_singular() )
        return;
 
    global $wp_query;
 
    /** Stop execution if there's only 1 page */
    if( $wp_query->max_num_pages <= 1 )
        return;
 
    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max   = intval( $wp_query->max_num_pages );
 
    /** Add current page to the array */
    if ( $paged >= 1 )
        $links[] = $paged;
 
    /** Add the pages around the current page to the array */
    if ( $paged >= 3 ) {
        $links[] = $paged - 1;
        $links[] = $paged - 2;
    }
 
    if ( ( $paged + 2 ) <= $max ) {
        $links[] = $paged + 2;
        $links[] = $paged + 1;
    }
 
    echo '<div class="navigation"><ul>' . "\n";
 
    /** Previous Post Link */
    if ( get_previous_posts_link() )
        printf( '<li>%s</li>' . "\n", get_previous_posts_link() );
 
    /** Link to first page, plus ellipses if necessary */
    if ( ! in_array( 1, $links ) ) {
        $class = 1 == $paged ? ' class="active"' : '';
 
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );
 
        if ( ! in_array( 2, $links ) )
            echo '<li>…</li>';
    }
 
    /** Link to current page, plus 2 pages in either direction if necessary */
    sort( $links );
    foreach ( (array) $links as $link ) {
        $class = $paged == $link ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
    }
 
    /** Link to last page, plus ellipses if necessary */
    if ( ! in_array( $max, $links ) ) {
        if ( ! in_array( $max - 1, $links ) )
            echo '<li>…</li>' . "\n";
 
        $class = $paged == $max ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
    }
 
    /** Next Post Link */
    if ( get_next_posts_link() )
        printf( '<li>%s</li>' . "\n", get_next_posts_link() );
 
    echo '</ul></div>' . "\n";
 
}

#STEP 2: Add to the templates using this call to the function above 

njengah_numeric_pagination();

#STEP 3 : Style the Pagination appropriately to fit your theme styles 

/** CSS Classes to Style the Pagination*/ 

.navigation li {
    
}
.navigation li a{
	
	
}

#3) WordPress Ajax Pagination Example

If you are looking for the Ajax pagination code in WordPress, I found an example on GitHub that is working very well and the code is in the form of a plugin.

I have customized it to make it a plugin for our tutorial and the code can be copied to a file and saved in zip format and installed as a plugin.

The following is the WordPress Ajax pagination example code:

<?php
/**
 * Plugin Name:       Njengah Ajax Pagination
 * Plugin URI:        https://njengah.com 
 * Description:       WordPress Ajax pagination example.
 * Version:           1.0.0
 * Author:            Joe Njenga
 * Author URI:        https://njengah.com 
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain:       cs-pagination
 * Domain Path:       /languages
 */

// Credit  - Casper Schultz 

class Njengah_Ajax_Pagination {

	protected $num_per_page;

	public function __construct() {
		$this->num_per_page = 5;
		$this->init();
	}

	protected function init() {
		add_action( 'init', array( $this, 'add_rewrite_rule' ) );
		add_filter( 'query_vars', array( $this, 'add_query_vars' ) );
		add_action( 'parse_request', array( $this, 'parse_request' ) );
	}

	/**
	 * Parse the incoming request and generate the result.
	 */
	function parse_request( $wp ) {

		if ( array_key_exists( 'cs-page', $wp->query_vars ) ) {

			$page = isset ( $wp->query_vars['cs-page'] ) ? $wp->query_vars['cs-page'] : 1;

			$args = array(
				'post_type'     => 'post',
				'post_per_page' => $this->num_per_page,
				'paged'         => $page,
			);

			$query  = new WP_Query( $args );

			// We need to know the total number of posts found.
			$values['total'] = $query->found_posts;

			// And the per page.
			$values['per_page'] = $this->num_per_page;

			$values['posts'] = array();

			// Lets only send the data we need.
			while ( $query->have_posts() ) {

				$query->the_post();

				$values['posts'][] = array(
					'ID'      => get_the_ID(),
					'title'   => get_the_title(),
				);
			}

			wp_reset_postdata();
			wp_send_json( $values );
		}
	}

	/**
	 * Add the needed query args.
	 */
	function add_query_vars( $query_vars ) {
		$query_vars[] = 'cs-page';

		return $query_vars;
	}

	/**
	 * Adds a rewrite rule for our custom pagination so that we can avoid using admin-ajax.
	 */
	function add_rewrite_rule() {
		add_rewrite_rule( '^cs-paginate/([0-9]+)/?', 'index.php?cs-page=$matches[1]', 'top' );
	}

	/**
	 * Flush rewrite rules.
	 */
	static function install() {
		flush_rewrite_rules();
	}
}


function njengah_ajax_pagination_init() {
	new Njengah_Ajax_Pagination();
}

njengah_ajax_pagination_init();

// Need to flush rewrite rules on activation.
register_activation_hook( __FILE__, array( 'Njengah_Ajax_Pagination', 'install' ) );

#4) WordPress Pagination for Custom Post Type

For custom post type pagination, you need to use the WP_query to check for the custom post type, and in the arguments, you pass the custom post type in the post_type and then use the pagination code to create the WordPress pagination for the custom post type.

The following is the code that you should add to the functions.php and replace the post_type with your respective custom post type slug:

<?php 

/**
 * WordPress Pagination for Custom Post Types  
 */ 
 
 <?php

 $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

	$args = array(
		 'post_type' => 'custom_post_type_name',
		 'posts_per_page' => 10,
		 'paged' => $paged
	);

	$loop = new WP_Query( $args );

	while ( $loop->have_posts() ) : $loop->the_post();
 
 // Custom post type content 
 
endwhile;
?>
<nav class="pagination">
     <?php
     $big = 999999999;
     echo paginate_links( array(
          'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
          'format' => '?paged=%#%',
          'current' => max( 1, get_query_var('paged') ),
          'total' => $loop->max_num_pages,
          'prev_text' => '&laquo;',
          'next_text' => '&raquo;'
     ) );
?>
</nav>
<?php wp_reset_postdata(); ?>

#5 Custom Query Pagination WordPress

The custom query pagination code in WordPress utilizes the WP_query to get the specific post we want to paginate and then combines the results of the query with the pagination code to apply the pagination to the specific posts we selected.

The following is an example of custom query pagination in WordPress.

<?php

//Custom Query 

$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
 
$args = array(
    'posts_per_page' => 5,
    'category_name' => 'gallery',
    'paged' => $paged,
);
 
$the_query = new WP_Query( $args );
?>
<!-- the loop etc.. -->

<?php

// Pagination 
$big = 999999999; // need an unlikely integer
 
echo paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '?paged=%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total' => $the_query->max_num_pages
) );

Conclusion

In this post, we have highlighted the different types of WordPress pagination and shared specific pagination codes to use for each case. This pagination code in WordPress can be added to existing themes or plugins and can as well be added to WordPress as a standalone plugin.

Similar Articles

Comments are closed.