Skip to content

Instantly share code, notes, and snippets.

@mdahlke
Created January 9, 2017 19:28
Show Gist options
  • Save mdahlke/3b5a23f990067e567ec7d2f560df19e3 to your computer and use it in GitHub Desktop.
Save mdahlke/3b5a23f990067e567ec7d2f560df19e3 to your computer and use it in GitHub Desktop.
Create custom pagination for custom WP queries
<?php
$paged = (int) ( get_query_var( 'result-page' ) ?: 1 );
$postsPerPage = get_option('posts_per_page');
$args = array(
'post_type' => 'news',
'posts_per_page' => $postsPerPage,
'paged' => $paged,
'orderby' => receive( 'news_orderby', 'date' ),
'order' => receive( 'news_order', 'DESC' ),
);
$news = new WP_Query( $args );
$totalPosts = $news->found_posts;
$resultsMin = ( ( $paged * $postsPerPage ) - ( $postsPerPage ) ) + 1;
$resultsMax = ( $paged * $postsPerPage );
if ( $resultsMin < 0 || $totalPosts === 0 ) {
$resultsMin = 0;
}
if ( $resultsMax > $totalPosts ) {
$resultsMax = $totalPosts;
}
if ( $news->have_posts() ) {
?>
<div class="results-count-wrap">
<div class="row">
<div class="col-xs-6">
Showing <strong><?= $resultsMin; ?></strong>-<strong><?= $resultsMax; ?></strong> of
<strong><?= $totalPosts; ?></strong>
results
found.<br>
</div>
<div class="col-xs-6">
<div class="pull-right">
<strong><?= pagination_page_of( $news->max_num_pages, $paged ); ?></strong>
</div>
</div>
</div>
</div>
<?php
while ( $news->have_posts() ) {
$news->the_post();
get_template_part( ATOMIC_MOLECULE . '/blog-index-post' );
}
custom_pagination( $news->max_num_pages, 2, $paged );
wp_reset_postdata();
}
<?php
function add_query_vars_filter( $vars ) {
$vars[] = 'result-page';
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
function custom_pagination( $numpages = '', $pagerange = 5, $paged = '' ) {
if ( empty( $pagerange ) ) {
$pagerange = 2;
}
if ( empty( $paged ) ) {
global $paged;
}
if ( empty( $paged ) ) {
$paged = 1;
}
if ( $numpages == '' ) {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if ( !$numpages ) {
$numpages = 1;
}
}
/**
* We construct the pagination arguments to enter into our paginate_links
* function.
*/
$pagination_args = array(
'base' => str_replace('%_%', (1 == $paged ? '' : "?result-page=%#%"), "?result-page=%#%"),
'format' => '?result-page=%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => false,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => true,
'prev_text' => __( '&laquo;' ),
'next_text' => __( '&raquo;' ),
'type' => 'plain',
'add_args' => false,
'add_fragment' => '',
);
$paginate_links = paginate_links( $pagination_args );
if ( $paginate_links ) {
echo '<nav class="custom-pagination">';
echo pagination_page_of( $numpages, $paged );
echo $paginate_links;
echo '</nav>';
}
}
function pagination_page_of( $numpages = '', $paged ) {
return '<div class="page-numbers page-num pull-right">Page ' . $paged . ' of ' . $numpages . '</div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment