Pretty paged permalinks in custom post type loop

The question:

I must be annoying your with all these permalink questions 🙂

The code I’m using for the loop is:

// hijack stupid WP globals to get pagination working...
global $wp_query;
$temp = $wp_query;

$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$wp_query = new WP_Query();
  'post_parent' => get_the_ID(),
  'post_type' => 'topic-reply',
  'posts_per_page' => 10,
  'order' => 'ASC',
  'paged' => $paged,
  while ($wp_query->have_posts()):

$wp_query = $temp;

The pagination works fine if permalinks are set to defaults, when clicking on page 2 link the URL I get is like:


The problem comes when I set the permalinks to a custom structure; when clicking on page 2, I get the first page URL:


instead of


(A live example here)

Does anyone know the rules I should add to set paged permalinks for the “topic-reply” post type?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

When you use paged on a single post, it’s checking for a paginated post, not pages of posts. Because your topics don’t have paginated content, it’s assuming it’s a mistake and redirecting to the ‘first’ page of the topic, long before your custom loop is ever touched. So, in this instance, paged is always going to return as 1. As a workaround, I’d register an EP Permalink for the topic. Something like this:

add_rewrite_endpoint( 'tpage', EP_PERMALINK );

Then, instead of checking for get_query_var( 'paged' );, check for get_query_var( 'tpage' ); and pass the value for that along to the custom query. Setting up that rewrite endpoint means that all permalinks compatible with the EP_PERMALINK bitmask (your topics are compatible) will accept a /tpage/XXXX structure added to the end of the url, where XXXXX can be anything you want (in this instance, you’d want to typecast it as an integer, probably an absolute one at that).


Something like this should work to get you an array of paginated links:

$links = paginate_links(array(
  'base' => trailingslashit( get_permalink( $temp->post->ID ) ) . '%_%',
  'format' => 'tpage/%#%',
  'type' => 'array'

From there, you could do something like this:

<div class="page-navi  clear-block">
  <?php foreach( $links as $link ){
    if( false !== strpos( $link, " class='page-numbers'" ) )
      $link = str_replace( " class='page-numbers'", " class='page page-numbers'", $link );
    echo $link;
  } ?>

I’m pretty sure that’d get you the same styles and the ‘current’ style for the links.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment