For my site, I have a custom post type video set to appear at at the URL http://site.url/videos. It is paginated so that there are 24 videos per archive page. However, I am not using the single.php to render a view for the video, I am instead displaying the video's contents via ajax on the archive page when clicked. I allow for linking to specific videos via javascript, which just selects and opens the desired video on page load (via the URL string).

I have rewrite rules in place that allow for site.url/videos/my-video to redirect to index.php?post_type=video which works great. However, for my paginated videos, I use single.php to perform a 301 redirect to the paginated archive page where that individual video is currently located.

My rewrite rule enabling this is as follows:

function video_rewrite() {
  add_rewrite_rule('videos/page/([0-9]{1,})/?$', 'index.php?post_type=video&paged=$matches[1]', 'top');`
add_action('init', 'video_rewrite');

and the redirect code on single-video.php

$post_id = $post->ID;
$args = array(
  'post_type' => 'video',
  'showposts' => -1,
  'orderby' => 'date',
  'order' => 'DESC',
$count = 0;
$video_query = new WP_Query($args);
if ($video_query->have_posts()) {
  foreach($video_query->posts as $key => $video_post) {
    if ($video_post->ID === $post_id) {
      $post_offset = $key;

$posts_per_page = $GLOBALS['videos_posts_per_page'];
$page_number_notrounded = $post_offset / $posts_per_page;
$page_number = round($page_number_notrounded, 0, PHP_ROUND_HALF_UP);
$page_number = $page_number + 1;
if ($page_number > 1) {
  $redirect_url = get_bloginfo('url').'/videos/page/'.$page_number.'/'.$post->post_name;
  $post_link = $redirect_url;

wp_redirect($post_link, 301);

For some reason, Wordpress appends pagination twice. Being 301 redirected to site.url/videos/page/2/my-video loads the following url: site.url/videos/page/2/my-video/page/2/

How can I prevent the pagination from being appended twice?

  • What does redirect code look like? – Rarst Sep 16 '15 at 16:36
  • @Rarst added code above – brooklynjb Sep 16 '15 at 19:32
  • Realizing wouldn't work anyways since the first page doesn't have pagination appended to it and would then result in an infinite loop. – brooklynjb Sep 18 '15 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.