Pagination for Custom Post types

Prev and Next button

$our_current_page = get_query_var( 'paged' );

$query = new \WP_Query(
   [
      'post_type'              => 'post-type-name',
      'post_status'            => 'publish',
      'posts_per_page'         => 3,
      'paged'                  => $our_current_page,
      'update_post_meta_cache' => false,
      'update_post_term_cache' => false,
   ]
);

    if ( $query->have_posts() ) {

      while ( $query->have_posts() ) {
         $query->the_post();
         the_title();
      } // end while

      previous_posts_link();
      next_posts_link( 'Next page', $query->max_num_pages );

   } // end if

Numbered Pagination

Create a Custom pagination function

/**
 * Custom pagination
 */
function custom_pagination( $query ) {

   $allowed_tags = [
      'span' => [
         'class' => [],
      ],
      'i'    => [
         'class' => [],
      ],
      'a'    => [
         'class' => [],
         'href'  => [],
      ],
   ];

   printf(
      '<nav class="ninetrade-pagination clearfix">%s</nav>',
      wp_kses(
         paginate_links(
            [
               'prev_text' => '<i class="fa fa-angle-left" aria-hidden="true"></i> ' . __( 'Previous', 'ninetrade' ),
               'next_text' => __( 'Next', 'ninetrade' ) . ' <i class="fa fa-angle-right" aria-hidden="true"></i>',
               'total'     => $query->max_num_pages
            ]
         ),
         $allowed_tags
      )
   );
}

Now use this custom function with the query

$our_current_page = get_query_var( 'paged' );

$query = new \WP_Query(
   [
      'post_type'              => 'post-type-name',
      'post_status'            => 'publish',
      'posts_per_page'         => 3,
      'paged'                  => $our_current_page,
      'update_post_meta_cache' => false,
      'update_post_term_cache' => false,
   ]
);

if ( $query->have_posts() ) {

   while ( $query->have_posts() ) {
      $query->the_post();
      //
      // Post Content here

      the_title();
      //
   } // end while

   wp_reset_postdata();

   custom_pagination( $query );

}

Leave a Reply