Wordpress - How to disable the single view for a custom post type?

Just setting the argument

'publicly_queryable'  => false

when you call register_post_type()


METHOD 1:

Redirect to a custom URL for single view, archive page is still publicly accessible.

You can use template_redirect hook to redirect for a custom post type, you can use any other URL you want to in place of home_url() and the error code in other argument.

<?php
add_action( 'template_redirect', 'wpse_128636_redirect_post' );

function wpse_128636_redirect_post() {
  if ( is_singular( 'sample_post_type' ) ) {
    wp_redirect( home_url(), 301 );
    exit;
  }
}
?>

METHOD 2:

Completely disable Single or Archive page from front-end; Works for a Custom post only.

A alternative approach is to specify value for param publicly_queryable while registering the custom post if you are ok with displaying a 404 page. [ Thanks @gustavo ]

'publicly_queryable'  => false

It hides single as well as archive page for the CPT, basically completely hidden from front-end but can be done for custom posts only.

This second solution is best suitable for the scenario where you need a Custom post for admin/back-end usage only.


A simpler way to do that can be passing the following args when registering the Custom Post Type

register_post_type('sample_post_type',array(
'labels' => array(
    'name' => _x('Sample Posts', 'post type general name'),
    'singular_name' => _x('Sample Post', 'post type singular name')
),
'public' => true,
'exclude_from_search' => true,
'show_in_admin_bar'   => false,
'show_in_nav_menus'   => false,
'publicly_queryable'  => false,
'query_var'           => false
));