How to redirect all single posts of a custom post type?

When creating a website or blog in WordPress with custom post types (CPT), there may be times when you do not want to show the single post, but to redirect it to a specific page.

When creating a website or blog in WordPress with custom post types (CPT), there may be times when you do not want to show the single post, but instead redirect it to a specific page.

Even if you do not directly link to the single post, it remains visible for search engines.

This simple tutorial will show you how to use a WordPress function to redirect all single posts of a custom post type.

For instance, we have CPT Testimonials.

All testimonials are displayed on the Testimonials page.

We don’t want visitors to be able to see single testimonials (no design for it, no link to them inside the website but, as previously said, for SEO we need a fix).

The goal is for each individual testimonial page to redirect to the main Testimonial page.

As we know, it is simple to create 301 redirections in the .htaccess file. However, we don’t want to hardcode all of those rules to redirect to a specific post/page slug because they may change in the future. Furthermore, the number of testimonials may increase, which is difficult to manage.

We will use a WordPress function to redirect all testimonials to a specific location (home, page, archive, etc.) as a workaround to avoid anyone accidentally landing on an unwanted location of our site.

add_action( 'template_redirect', 'redirect_single_custom_post_type' );
function redirect_single_custom_post_type(){
    if ( ! is_singular( 'testimonial' ) )
        return;
    wp_redirect( get_page_link( PAGE_ID ), 301 );
    exit;
}

Of course, please:

  • Change ‘testimonials’ to match your CPT’s slug.
  • Replace ‘PAGE_ID’ with the ID of the page to which you want your CPT single posts to redirect.

Place this code in functions.php of your theme.

Is there a plugin for this?

If you don’t feel comfortable to change theme files, you can try Simple 301 Redirects by BetterLinks. Although I try to use as few plugins as possible, this one is very useful, because it allows wildcard expressions. This means that you can easily redirect all your CPT posts with only one directive:

Redirect plugin
  • Change ‘/testimonials/*’ to match your CPT’s slug in REQUEST field.
  • Replace ‘/testimonials/’ with the slug of the page to which you want your CPT single posts to redirect.

Good read

Nikola Stulic

Father of two beautiful girls. WordPress developer trapped inside the mind of a math teacher (and vice versa). Often doodles the Greek letter Xi. Loves to wear suits and ties.

WordPress contributor, educator, translator. WordCamp Europe organizer.

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.