Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I created a 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,
    'show_in_nav_menus' => false,
    'exclude_from_search' => true
));

How can i disable the single post view for this specific post type? Displaying a simple 404 is fine, or redirecting to the homepage. This is inside a plugin, so i can't create a single-sample_post_type.php file to setup an empty page.

share|improve this question

4 Answers 4

up vote 9 down vote accepted

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() {
  $queried_post_type = get_query_var('post_type');
  if ( is_single() && 'sample_post_type' ==  $queried_post_type ) {
    wp_redirect( home_url(), 301 );
    exit;
  }
}
?>
share|improve this answer
    
A good solution. I found it was helpful to only perform this redirect for non-authenticated users, by checking to see if get_current_user_id() evaluates to 0. –  RevNoah Jun 29 at 13:25
    
Good to know :) –  sven Jun 30 at 2:11

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
));
share|improve this answer
1  
You would actually need publically_querable to be true for Post Type Archives to work. –  Howdy_McGee Nov 12 '14 at 19:42
    
This does not work for me. It justs redirects back to the homepage when trying to go to the archive –  Yahya Uddin Jul 15 at 15:51

One. From your functions file.

add_action( 'template_redirect', 'redirect_cpt_singular_posts' );
    function redirect_cpt_singular_posts() {
      if ( is_singular('your-cpt-slug') ) {
        wp_redirect( home_url(), 302 );
        exit;
      }
    }

Two. From your single.cpt.php file:

<?php wp_redirect( home_url() ); exit; ?>
share|improve this answer

Just setting the argument

'publicly_queryable'  => false

when you call register_post_type()

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.