Stop WordPress redirecting comment-page-1 to the post page?

Great question! WordPress assigns your comment page number to the query var 'cpage' which gets set when your URL has /comment-page-1/ at the end. So your culprit is in the redirect_canonical() function, line 192 of /wp-includes/canoncial.php.

if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) {

Since the redirect_canonical() function gets set as an action what we can do is to insert our own function to be called instead, have our function set the 'cpage' query var to false, call redirect_canonical(), and then set 'cpage' back to what it was; that will keep WordPress from redirecting on you.

To insert your own function you need to call the two hook 'init' and 'template_redirect' like so being sure to set the 'init' hook to be called after the do_action() inside WordPress core that adds redirect_canonical():

add_action('init','yoursite_init',11); //11=lower priority
function yoursite_init() {
  remove_action('template_redirect','redirect_canonical');
  add_action('template_redirect','yoursite_redirect_canonical');
}

add_action('template_redirect','yoursite_redirect_canonical');
function yoursite_redirect_canonical($requested_url=null, $do_redirect=true) {
  $cpage = get_query_var('cpage');
  set_query_var('cpage',false);
  redirect_canonical($requested_url, $do_redirect);
  set_query_var('cpage',$cpage);
}

Then of course you need to do something with your 'cpage'. You can either check for the value returned by get_query_var('cpage') or you can add another hook to allow you to create a comment-specific template which is what I did. It will add look for a theme template file with the same as it would normally load but with [comments].php at the end of the name instead of .php, i.e. single[comments].php. Note that I set priority for this filter to be 11; you may need to set to an even larger number if a plugin you use adds itself after your hook:

add_filter('single_template','yoursite_single_template',11);
function yoursite_single_template($template) {
  if (get_query_var('cpage'))
    $template = str_replace('.php','[comments].php',$template);
  return $template;
}

And here’s the proof that it all works!

Screenshot of Custom WordPress Page Template for Comments
(source: mikeschinkel.com)

Leave a Comment