How to redirect all Single Posts of a Custom Post Type in WordPress

While developing a website or blog in WordPress with Custom Post Type’s there may come a time when you do not want to actually display the Single Post. Even if you do not link directly to the Single Post it still exists on the server. The best work around to avoid anyone accidentally stumbling upon an undesired location of your website is to use a WordPress PHP function to redirect all of your Single Posts from that Custom Post Type to a specific Page. In this tutorial we will teach you how to redirect all Single Posts of a Custom Post Type via a WordPress function.

Redirect all Single Posts of a Custom Post Type using a WordPress Function

In order to redirect all Single Posts of a Custom Post Type in WordPress, we will need to add a PHP filter to the WordPress functions file. Open your functions.php file then copy and paste the code below, you will need to reference the ‘Items to Note’ below in order to adjust the code to work with your specific Custom Post Type and desired redirect.

PHP

add_action( 'template_redirect', 'redirect_post_type_single' );
function redirect_post_type_single(){
    if ( ! is_singular( 'YOUR-CUSTOM-POST-TYPE' ) )
        return;
    wp_redirect( get_page_link( YOUR-PAGE-ID ), 301 );
    exit;
}

Items to Note:

  • Change ‘YOUR-CUSTOM-POST-TYPE’ to the name of the Custom Post Type you would like to have redirected.
  • Change ‘YOUR-PAGE-ID’ to the ID of the Page you would like your Custom Post Type’s Single Posts to redirect to.
  • If you followed the instructions correctly all of the Single Posts of your Custom Post Type will now be redirected to your desired location.

Troubleshooting

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible. Please do not email us with problems regarding this tutorial, only comments will be responded to.