WordPress Logo

Just a quick one. I’ve been creating a theme that uses three different post custom post types and I just couldn’t get pagination working. By pagination I just mean a link to see older / newer posts. This was working fine for standard posts but not my custom post types.

My Set up

So for example I had a custom post type called Events and I was wanting to display these in a page called page-events.php, so the paginated pages would have the slug, domain/events/page/2 this just would not work.

  $temp = $wp_query; 
  $wp_query = null; 
  $wp_query = new WP_Query(); 

  while ($wp_query->have_posts()) : $wp_query->the_post(); 

  <!-- LOOP: Usual Post Template Stuff Here-->

<?php endwhile; ?>

    <?php previous_posts_link('« Newer') ?>
    <?php next_posts_link('Older »') ?>

  $wp_query = null; 
  $wp_query = $temp;  // Reset

Code from CSS Tricks

The Solution

After a little bit of searching around I finally found the answer. Its so straight forward, simply call your page something other than what you have called your CPT. So in my case I renamed my page from events to latest-events in the WordPress admin and therefore in my theme my PHP file was now called latest-events.php. With this change made my pagination worked a treat.

Just wanted to document this as I’m sure many others will experience this annoying issue. If this helps just one person it will be worth while.

Thanks for reading

  • Adam

    Hi, I’m having the same problem and I want to try out your solution but I’m not sure I get it… Do you mean that the CPT slug name has to be different from the descriptive name of the CPT? How does this fit in the WordPress template hierarchy? (https://developer.wordpress.org/files/2014/10/template-hierarchy.png)

    • richarddale

      Hi Adam Only just seen this comment, sorry about that. Yes thats exactly what I mean. When the slug had the same name as the CPT it wouldn’t work. This was a few months back now so perhaps its now been addressed in a fix. I’m not sure what you mean by how does this fit into the template hierarchy.

      • Adam

        No worries! We ended up fixing our issue with GET variables and mod_rewrite instead… It didn’t look nice code-wise, but we had a deadline.
        The template hierarchy shows what files WordPress accesses when you type in a web address. I was just wondering how the path looked for you in the template hierarchy =) It’s a bit hard to explain…

        Anyway, don’t know if the issue is fixed yet. Haven’t revisited the problem…
        Thanks for your answer, even though it was a bit late =)

        • Richard Dale

          No problem mate thanks for visiting my website.

        • richarddale

          No worries thanks for visiting my website 🙂