Skip to content

Instantly share code, notes, and snippets.

@bebaps
Created February 22, 2017 01:55
Show Gist options
  • Save bebaps/0609812af291183583e2d910a49f5c67 to your computer and use it in GitHub Desktop.
Save bebaps/0609812af291183583e2d910a49f5c67 to your computer and use it in GitHub Desktop.
WordPress pagination when using a custom query within a custom page template
<?php
// An older method, a hack really that works by reseting the default WP_Query in order to trick WordPress into thinking that our custom query is the default query
// Not a fan of this method, but post it because it is still a reliable alternative
// Store the orginal, default WP_Query in a temp variable
$temp = $wp_query;
// Flush the default WP_Qeury
$wp_query = null;
// Set up our custom query, making sure to name it the same as the global $wp_query that WordPress expects
// Note that because we are hijacking the orginal $wp_query, we dont need to manually set the $paged variable
$args = [
'post_type' => 'testing',
'posts_per_page' => 3,
'paged' => $paged
];
$wp_query = new WP_Query($args);
while ( $wp_query->have_posts() ) : $wp_query->the_post();
// Loop stuff
endwhile;
// We can now use any pagination function that works out of the box
the_posts_pagination();
// Be sure to flush our hacked $wp_query
$wp_query = null;
// And restore it to its orginal self for WordPress to work with
$wp_query = $temp;
<?php
// This is a newer, better method
// First, grab the current page number from the URL
// If using a static front page, use 'page' instead of 'paged'
$the_page = get_query_var('paged');
// Standard custom query, ensuring to add the 'paged' parameter
$args = [
'post_type' => 'testing',
'posts_per_page' => 3,
'paged' => $the_page
];
$query = new WP_Query($args);
while ( $query->have_posts() ) : $query->the_post();
// Loop stuff
endwhile;
// Set up pagination
// Since this is a custom query, on a custom page template, we need to manually tell the function how many total pages can be paginated
echo paginate_links([
'total' => $query->max_num_pages
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment