WordPress paginate WP_Query

September 2, 2015

For those of you that are making custom post types on your WordPress blog and using WP_Query to list posts in those types — you may have noticed that pagination doesn’t work.

Here is an example template that will pull all posts with a custom post type “videos’ and display them, five at a time and paginated.

<?php
/**
 * Template Name: Videos
 *
 * Selectable from a dropdown menu on the edit page screen.
 */

get_header(); ?>

<div id="primary" class="content_area">
  <main id="main" class="site-main" role="main">

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
    'post_type' => array('video'),
    'posts_per_page' => "5",
    'paged' => $paged
);

// the query
$the_query = new WP_Query( $args );

// Pagination fix
    $temp_query = $wp_query;
    $wp_query   = NULL;
    $wp_query   = $the_query;
?>

<?php if ( $the_query->have_posts() ) : ?>

  <!-- the loop -->
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <article class="post type-post status-publish format-standard hentry">
      <header class="entry-header">
        <h2 class="entry-title">
          <a href="<?php the_permalink(); ?>">
            <?php the_title(); ?>
          </a>
        </h2>
        <div class="entry-content">
          <?php the_content(); ?>
        </div>
      </header>
    </article>
    <?php endwhile; ?>
    <!-- end of the loop -->
    <?php
    the_posts_pagination( array(
        'prev_text'          => __( 'Previous page', 'twentyfifteen' ),
        'next_text'          => __( 'Next page', 'twentyfifteen' ),
        'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>',
    ) );
    ?>

    <?php wp_reset_postdata(); ?>

    <?php else : get_template_part( 'content', 'none' ); endif; ?>

  </main><!-- #main -->
</div><!-- #primary -->

<?php get_footer(); ?>