WordPress: Adding pagination to custom post types

Original source: http://callmenick.com/post/custom-wordpress-loop-with-pagination

Smug Piggy for the Latest Men's & Women's T-shirts

The following code is excellent for creating pagination for your custom post types. Place the following in your functions.php:

function custom_pagination($numpages = '', $pagerange = '', $paged='') {

if (empty($pagerange)) {
$pagerange = 2;
}

global $paged;

if (empty($paged)) {
$paged = 1;
}

if ($numpages == '') {
global $wp_query;

$numpages = $wp_query->max_num_pages;

if(!$numpages) {
$numpages = 1;
}
}

$pagination_args = array(
'base'            => get_pagenum_link(1) . '%_%',
'format'          => 'page/%#%',
'total'           => $numpages,
'current'         => $paged,
'show_all'        => False,
'end_size'        => 1,
'mid_size'        => $pagerange,
'prev_next'       => True,
'prev_text'       => __('«'),
'next_text'       => __('»'),
'type'            => 'plain',
'add_args'        => false,
'add_fragment'    => ''
);

$paginate_links = paginate_links($pagination_args);

if ($paginate_links) {
echo "<div class='pagination'>";
echo "<div class='left'>Page " . $paged . " of " . $numpages . "</div> ";
echo "<div class='right'>" . $paginate_links . "</div> ";
echo "</div>";
}
}

The following is placed on your custom template page.

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

$my_query_args = array(
'post_type' => 'custom',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => 8,
'paged' => $paged
);

$my_query = new WP_Query( $my_query_args );
?>

<?php if (function_exists(custom_pagination)) { ?>
<div class="col-sm-12 inner-sm">
<?php custom_pagination($my_query->max_num_pages, "", $paged); ?>
</div>
<?php } ?>

3 responses to “WordPress: Adding pagination to custom post types

  1. Wow, I have added pagination to custom post type seamlessly (Easily). Although I had some issues, because I have copied and paste whole code and forget to delete opening PHP tag.

    Thanks Admin.

Leave a Reply to Mike Little Cancel reply

Your email address will not be published. Required fields are marked *