Skip to content

Instantly share code, notes, and snippets.

@nkarpeev
Created December 11, 2018 14:35
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nkarpeev/5fb28d13e0aa02494d1464ecea374fd1 to your computer and use it in GitHub Desktop.
Save nkarpeev/5fb28d13e0aa02494d1464ecea374fd1 to your computer and use it in GitHub Desktop.
Using the_posts_pagination for custom page template WordPress
// Define page_id
$page_ID = get_the_ID();
// Define paginated posts
$page = get_query_var( 'page' );
// Define custom query parameters
$args = array(
'post_type' => array( 'post', 'book', 'movie' ), // post types
'posts_per_page' => 5,
'paged' => ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1
);
// If is_front_page "paged" parameters as $page number
if ( is_front_page() )
$args['paged'] = $page;
// Instantiate custom query
$custom_query = new WP_Query( $args );
// Custom loop
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
/**
* Displaying content
*
* the_title(), the_permalink(), the_content() etc
* Or see Twentysixteen theme page.php
* get_template_part( 'template-parts/content', 'page' );
*
*/
endwhile;
/**
* Pagination parameters of the_posts_pagination() since: 4.1.0
*
* @see the_posts_pagination
* https://codex.wordpress.org/Function_Reference/the_posts_pagination
*
*/
$pagination_args = array(
'prev_text' => __( 'Previous page', 'theme-domain' ),
'next_text' => __( 'Next page', 'theme-domain' ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'theme-domain' ) . ' </span>'
);
/**
* Fix pagination link base
*
* If in paginated posts w/o multiple loop
*
*/
if ( ! is_front_page() && 0 < intval( $page ) )
$pagination_args['base'] = user_trailingslashit(
untrailingslashit( get_page_link( $page_ID ) ) . '/page/%#%'
);
/**
* Fix Pagination with $GLOBALS['wp_query'] = {custom_query}
*
* @see get_the_posts_pagination use $GLOBALS['wp_query']
* https://developer.wordpress.org/reference/functions/get_the_posts_pagination/#source-code
*
*/
$GLOBALS['wp_query'] = $custom_query;
the_posts_pagination( $pagination_args );
else :
/**
* Empty Post
*
* Run your stuff here if posts empty
* Or see Twentysixteen theme page.php
* get_template_part( 'template-parts/content', 'none' );
*/
endif;
wp_reset_query(); // Restore the $wp_query and global post data to the original main query.
@tdiluzio
Copy link

Great! Thank you very much for sharing 👍

@akkis
Copy link

akkis commented Sep 14, 2020

You are my hero! Thank you!

@maltemichels
Copy link

So lucky, I found this at last. Thank you so much for sharing this so straight forward.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment