Skip to content

Instantly share code, notes, and snippets.

@aaronsummers
Last active April 18, 2019 07:49
Show Gist options
  • Save aaronsummers/19008696069c93899e458af54dd861b4 to your computer and use it in GitHub Desktop.
Save aaronsummers/19008696069c93899e458af54dd861b4 to your computer and use it in GitHub Desktop.
Adding pagination to custom post type archives
<?php
global $wp_query;
// Make Pages work with the loop
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
// Args
$args = array(
'post_type' => 'custom_post_type',
'posts_per_page' => 8,
'paged' => $paged
);
// The Query
$the_query = new WP_Query( $args );
// Store the orignal global $wp_query object
$original_query = $wp_query;
$wp_query = $the_query;
// The Loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
$the_query->the_post(); ?>
<div> loop stuff here </div>
<?php endwhile; // End The Loop
// Using https://wordpress.org/plugins/wp-paginate/
// But could be standard pagination here
if(function_exists('wp_paginate')):
wp_paginate();
endif;
// Restore original Post Data
wp_reset_postdata();
$wp_query = $original_query;
@aaronsummers
Copy link
Author

aaronsummers commented Apr 10, 2018

If we don't store the original query objecy then the pagination will always show 12 pages items.

If you see a 404 page when trying to view page 2, then you need to update the default wordpress show posts figure.

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