How to Create WordPress Pagination for Custom Post Types

WordPress Custom Post Type PaginationCreating pagination for custom post types should not be a challenge since you can repurpose the same idea we used here – how to create custom query pagination in WordPress. We need to query the custom post type then display the queries posts that in that post type or in several post types.

In this post, I am going to show you how to create WordPress pagination for the custom post types. The pagination will be similar to this numeric pagination. We will create a custom query that gets all the custom post types then display the custom post types with the loop and with number pagination.

Create a Custom Post Type

The first step is to create a custom post type using the following code:

/**
  * Custom Post Type - register_post_type()
  * @description-  Njengah Tutorial Custom Post Type Example 
  * @link -https://gist.github.com/Njengah/839466b773085ac2430772e081357cee
  *
  */ 


	add_action('init',  "njengah_tutorial_cpt");
  
  
	function njengah_tutorial_cpt(){
		
		$labels = array(
				'name' 			     =>   _x('Tutorials', 'post type general name'),
				'singular_name'    	 =>   _x('Tutorial', 'post type singular name'),
				'menu_name'          =>   _x('Tutorials', 'admin menu'),
				'name_admin_bar'     =>   _x('Tutorial', 'add new on admin bar'),
				'add_new'		  	 =>   _x('Add New', ''),
				'add_new_item'    	 =>   __('Add New tutorial'),
				'edit_item'        	 =>   __('Edit Tutorial'),
				'new_item'        	 =>   __('New Tutorial'),
				'all_items'        	 =>   __('All Tutorial'),
				'view_item'        	 =>   __('View Tutorial'),
				'search_items'    	 =>   __('Search Tutorials'),
				'not_found'       	 =>   __('No Tutorials found'),
				'not_found_in_trash' =>   __('No Tutorials found in Trash'), 
				'parent_item_colon'  =>   __('Parent Tutorials:'),
				
		);

			$args = array(
				'hierarchical'       =>  true,     
				'labels'             =>  $labels,
				'public'             =>  true,
				'publicly_queryable' =>  true,  
				'description'        => __('Description.'),
				'show_ui'            =>  true, 
				'show_in_menu'       =>  true,
				'show_in_nav_menus'	 =>  true,			
				'query_var'          =>  true,
				'rewrite'            =>  true,
				'query_var'          =>  true,
				'rewrite'            =>  array('slug' => 'tutorial'),
				'capability_type'    =>  'page',
				'has_archive'        =>  true, 
				'menu_position'      =>   22,
				"show_in_rest"       =>  true,
				'supports'           =>  array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'revisions', 'page-attributes', 'custom-fields' )
			); 

			register_post_type('tutorial', $args);
		
		
	}

Add this code to your functions.php file and you will see the custom post type ‘Tutorials’ appear on your WordPress dashboard.

WordPress Pagination for Custom Post Type

This code can be changed to suit your specific custom post type. The custom post type can also be created using the custom post type generation plugins.

Create a Page Template to Display Custom Post Types

We need to create a custom page template that will be used to display the custom post types using the WordPress loop.

To create a custom page template you should create a new file in the root folder of your theme.

Name the file – custom -page.php or any other name that is descriptive of the custom post type, for example for the custom post type created above the name could be tutorials-page.php.

In this file add the header of the custom page template using the following code and save the changes:

<?php
/**
 * Template Name: Tutorials Template
 */
 
 get_header(); 

You should now see the custom page template is visible in your page attributes template option as shown below:

Create WordPress Pagination for Custom Post Type

Create Custom Post Type Custom Query

The custom query is the first step that will allow us to query the existing custom post types and display them on the custom page template we created in the preceding step.

The following is the code that will query the tutorials custom post type and retrieve the first two posts then display them on the custom page template we created above.

<?php
/**
 * Template Name: Tutorials Template
 */
 
 get_header(); 
 
 
 // Step 1 : Create Custom Query 
 
 $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
 
  $args = array(
               'posts_per_page' => 2,// query last 2 posts  
			   'post_type' => 'tutorial', 
               'paged' => $paged
             );
			 
$customPostQuery = new WP_Query($args);


?>

Display Tutorial Custom Posts in the Custom Page Template

The following is the code that will query the custom post type and display them on the custom page template :

<?php
/**
 * Template Name: Tutorials Template
 */
 
 get_header(); 
 
 
 // Step 1 : Create Custom Query 
 
 $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
 
  $args = array(
               'posts_per_page' => 2,// query last 2 posts  
			   'post_type' => 'tutorial', 
               'paged' => $paged
             );
			 
$customPostQuery = new WP_Query($args);


?> 

<!-- Step 2: Display the Posts we Queried in the Step 1 -->

<div class="wrap">
 
	<div id="primary" class="content-area">
		
		<main id="main" class="site-main" role="main">
		
			<?php
			
			if($customPostQuery->have_posts() ): 
			
               while($customPostQuery->have_posts()) :
                   
				       $customPostQuery->the_post();
					   
					     global $post;
                ?>
		
		          <div class ="inner-content-wrap">
				  
						<ul class ="cq-posts-list">
						
						 <li>
						   <h3 class ="cq-h3"><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h3>
								<div>
								  <ul>
									<div>
											<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
									</div>
								  </ul>
								  
								  <ul>
											<p><?php echo the_content(); ?></p>
								  </ul>
								
								</div>
						  </li>
						</ul>
				</div> <!-- end blog posts -->
						  
			<?php endwhile; 
			
	     endif; 
	 
			 wp_reset_query();

Create WordPress Custom Post Pagination Function

In this step, we should now create a custom post type pagination function that will be added to the theme functions and will be called after the loop displays the custom post types.

The following code should be added to the functions.php to create custom post type pagination function.

    //  Custom post type pagination function 
	
    function cpt_pagination($pages = '', $range = 4)
    {
        $showitems = ($range * 2)+1;
        global $paged;
        if(empty($paged)) $paged = 1;
        if($pages == '')
        {
            global $wp_query;
            $pages = $wp_query->max_num_pages;
            if(!$pages)
            {
                $pages = 1;
            }
        }
        if(1 != $pages)
        {
            echo "<nav aria-label='Page navigation example'>  <ul class='pagination'> <span>Page ".$paged." of ".$pages."</span>";
            if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo; First</a>";
            if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo; Previous</a>";
            for ($i=1; $i <= $pages; $i++)
            {
                if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
                {
                    echo ($paged == $i)? "<li class=\"page-item active\"><a class='page-link'>".$i."</a></li>":"<li class='page-item'> <a href='".get_pagenum_link($i)."' class=\"page-link\">".$i."</a></li>";
                }
            }
            if ($paged < $pages && $showitems < $pages) echo " <li class='page-item'><a class='page-link' href=\"".get_pagenum_link($paged + 1)."\">i class='flaticon flaticon-back'></i></a></li>";
            if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo " <li class='page-item'><a class='page-link' href='".get_pagenum_link($pages)."'><i class='flaticon flaticon-arrow'></i></a></li>";
            echo "</ul></nav>\n";
        }
  }

Call Custom Post Type Pagination Function in Page Template

Since we have created the custom post type pagination function and we have already run the loop and displayed the custom post types, we now need to add the pagination function at the bottom of the custom page template so that we display the pagination.

The following is the code that should be used to check if the custom post pagination function exists and if it does we should call it to display the pagination

// Step  3 : Call the Pagination Function Here  
			 
  if (function_exists("cpt_pagination")) {
				
   cpt_pagination($customPostQuery->max_num_pages); 
			 
}

We have created custom post type, a custom page template,  added custom post type pagination function and displayed both the custom post types with a query and the custom post type pagination function.

Custom Post Type Pagination Styles

You need to add the styles to the custom post type pagination using the following code :

/**
 * Custom Post Type Pagination Styles
 * @author Joe Njenga
 */ 

.pagination {
   clear:both;
   position:relative;
   font-size:16px; 
   line-height:13px;
   float:right; 
	list-style-type:none;
	width:100%
}
.pagination span, .pagination a {
   display:block;
   float:left;
   margin: 2px 2px 2px 0;
   padding:6px 9px 5px 9px;
   text-decoration:none;
   width:auto;
   color:#fff; 
   background: #237697; 
}
.pagination a:hover{
   color:#fff;
   background: #000; 
}
.pagination .current{
   padding:6px 9px 5px 9px;
   background: #999; 
   color:#fff;

We are ready to view the result of this code. To view the custom post type pagination, you need to create a new page with the custom page template we created in the second step.

custom post type pagination function

After creating this page, you should see the page display the custom post type we queried and the pagination we created as shown in the image below:

custom post type pagination

Final Thoughts

To create custom post-type pagination, you need to create the custom page template, add the custom query to get all the custom posts you want to display, and call the custom pagination function that you add to the functions.php.  To get this full code I have added it to the git repo and you can access it here – WordPress Custom Post Type Pagination.

Similar Articles

Comments are closed.