How add pagination to WordPress custom post type?

Pagination is WordPress is builtin and it works as we put the WordPress standard code. We have some great plugins available that we can use too. Let say we have a case where we have WordPress custom post type and we want the normal pagination on that. We can very easily do that in WordPress by using following two functions:

previous_posts_link( 'Older Posts' );
next_posts_link( 'Newer Posts', $custom_query->max_num_pages );

We can also consider few more things before we write the pagination code. Let say we have custom post_type = product and and we want to show 8 published recent products per page. Following is the code that does the pagination:

// Define custom query parameters
$custom_query_args =  array(
		'post_type'   => 'product',
		'post_status' => 'publish',
		'ignore_sticky_posts' => 1,
		'posts_per_page' => 8
		'orderby' => 'DESC'
	);

// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );

// Pagination fix
$temp_query = $wp_query;
$wp_query   = NULL;
$wp_query   = $custom_query;

// Output custom query loop
if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) :
        $custom_query->the_post();
        // Loop output goes here
    endwhile;
endif;
// Reset postdata
wp_reset_postdata();

// Custom query loop pagination
previous_posts_link( 'Previous' );
next_posts_link( 'Next', $custom_query->max_num_pages ); // This max_num_pages is really important

// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
Share