1

TL;DR

Does anybody know how I can disable single pages and archives for custom post types while keeping the preview mode?


I'm looking for a way to disable the single and archive pages for a custom post type, because the posts will only be shown in the archive of a custom taxonomy that is assigned to the posts. This would usually be easily achieved by setting 'publicly_queryable' => false while creating the CPT.

Now, here's the twist: I still want to be able to use the preview mode for the posts, so I can check my changes on the post before I save them. Since setting 'publicly_queryable' => false will also disable the preview page I'm stuck between having single pages as duplicate content or not being able to see the drafts or changes of posts.


Based on the answer from Cesar (thanks!) I'm using following solution, which also shows how to keep the preview mode and redirects to the archive of the taxonomy, as explained above.

add_action('template_redirect', 'post_redirect', 99);

function post_redirect()
{
    global $post;
    if ((is_post_type_archive('post_type') || is_singular('post_type')) && !is_preview())
    {
        $post_terms = wp_get_post_terms($post->ID, 'taxonomy');
        if($post_term = $post_terms[0])
        {
            wp_redirect(get_term_link($post_term->term_id) . '#' . $post->post_name, 301);
            die();
        }
    }
}

I'm still interested in a solution without redirects, in case thats possible.

2

You can redirect, when someone tries to see the archive or the single of your custom post type, just redirect them to another page, just put this in your functions.php

add_action( 'template_redirect', 'theme_redirects', 99 );

function theme_redirects() {
    if ( is_post_type_archive( 'post_type_slug' ) || is_singular( 'post_type_slug' ) ) {
     wp_redirect( 'my_url' );
         die();
  }
}

See references:

is_post_type_archive

is_singular

template_redirect

  • Thanks, that seems like it would work. I'd rather not use redirects though. I'll leave the question open for a while in case someone comes around with a solution without redirects. Otherwise I'll accept it. – taymless Jul 20 '17 at 8:34

Your Answer

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

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