How to Create Custom Query Pagination In WordPress With an Example

How to Create Custom Query Pagination In WordPressCreating custom query pagination in WordPress is one of the most sort-after pagination solutions for blog posts and custom post types.  If you want to create custom query pagination in your WordPress blog, this post will guide you.  Ideally, custom query pagination involves using different query parameters to build pagination of WordPress post that is based on this query.

In the previous tutorial, I explained in detail how you can add numeric pagination in WordPress as well as how to create thumbnail previous and next post pagination, and how to split a post into multiple pages using pagination.  I also shared a number of WordPress pagination code that you can use in your blog to add your preferred pagination option. In this post, I will expound on how to build and implement custom query pagination on your WordPress site.

Custom Query Pagination

As I have mentioned in the introduction, the custom query pagination consists of three parts that include: the custom query, the code to display the pagination and some styles to make the pagination look good. We will break down this custom query pagination code into these three steps:

Create a Custom Query  of Post or Custom Posts

The first step is to create a query that is basically an array of arguments that we intend to use in the custom query.

To display this custom query pagination let us begin by creating a custom page template where we will add the code for the custom query pagination.

The following is the example of the custom page template with the custom query code:

<?php
/**
 * Template Name: CQ Pagination
 *
 */
 
 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 5 posts  
               'paged' => $paged
             );
			 
$customQuery = new WP_Query($args);

This code simply creates a custom page template that you can see under the page attributes as shown in the image below:

How to Create Custom Query Pagination In WordPress

The query can have several arguments but in this case, we have only limited to the ‘posts_per_page’   which is the number of posts we want to display on the page.

We can also specify the post type using ‘post_type’, orderby, author and much more. The following is an example of another query for the custom post type named ‘book’:

//Get current author to use in the query 

$current_author = ( isset($_GET ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval( $author ) );

/* set the arguments for the query
$args = array(
	'post_type'	        =>	array( 'goal' ),
	'orderby'	        =>	'date',
	'order'		        =>	'desc',
	'posts_per_page'    =>	10,
	'paged'		        =>	get_query_var( 'page' ) ? get_query_var( 'page' ) : 1,
	'author'	        =>	$current_author->ID
);

// Instantiate the query
$query = new WP_Query( $args );

After we build the $args and instantiate the query, we are now ready to display the posts in the loop and add the custom query in the next step.

Display Queried Posts in Custom Page Template

To display the queried posts the code has been added to the original custom template code and the full code is as follows:

<?php
/**
 * Template Name: CQ Pagination
 *
 */
 
 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 5 posts  
               'paged' => $paged
             );
			 
$customQuery = 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($customQuery->have_posts() ): 
			
               while($customQuery->have_posts()) :
                   
				       $customQuery->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 a Pagination Function

In this final step, we need to create the pagination function that we will use in the custom page template above to display the custom query pagination. To create the pagination function we need to add the following code to the functions.php file:

//  Custom pagination function 
	
    function cq_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 the Pagination Function in Custom Template

The final step is to call the function we added above in the template so that the pagination is displayed. To call this function we should use the following code:

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

Final code that creates a custom page template with this pagination function should be as follows:

<?php
/**
 * Template Name: CQ Pagination
 *
 */
 
 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 5 posts  
               'paged' => $paged
             );
			 
$customQuery = 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($customQuery->have_posts() ): 
			
               while($customQuery->have_posts()) :
                   
				       $customQuery->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();
			 
			// Step  3 : Call the Pagination Function Here  
			 
			if (function_exists("cq_pagination")) {
				
				  cq_pagination($customQuery->max_num_pages); 
			 
			}
					
			?>	
	
			</main><!-- #main -->
			
		</div><!-- #primary -->
			
	</div><!-- .wrap -->
	
<!----end of page-------->
		  
<?php get_footer();	?>

If you followed every step the right way you should have the pagination as seen in the image below:

How to Create Custom Query Pagination In WordPress

Style the Custom Query Pagination

The last step is to add the styles to the custom pagination to make it match the styles and design of the theme. The following is the CSS styles that you should add to the stylesheet to style this custom pagination:

/**
 * CQ 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;
}

After you add these pagination styles the final look of the custom pagination should be as shown on the image below:

How to Create Custom Query Pagination In WordPress

Final Thoughts

In this post, we have outlined the step by step way of adding custom query pagination to your WordPress blog. These steps include; creating the query, creating a custom page template to display the custom queried posts with pagination and adding a pagination function to the functions.php file. Finally do not forget to call the pagination function and add the appropriate styles that match the design of your WordPress theme.

Comments are closed.