Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save HDDen/1938139b791b66541a42db642d265d9f to your computer and use it in GitHub Desktop.
Save HDDen/1938139b791b66541a42db642d265d9f 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment