Comprehensively Restrict Post Type Taxonomy to Logged-in Users

I’ve faced similar situations (say a client wants to see how a custom post type and/or taxonomy behaves before they’re ready for the general public to see it). In those cases I’ll use something like the following code snippet, added either to the plugin file (assuming I’ve built the CPT/taxonomy as a plugin) or directly in the active theme’s functions.php:

/**
 * IN-DEVELOPMENT REDIRECTS
 * While specified areas are under development, redirect users to home page if not logged in
 */
add_filter( 'wp', 'f040925b_redirect', 0 );
function f040925b_redirect( $content ) {
    global $post;
    if(
        (
            $post->post_type == '[custom_post_type_name]'
            ||
            is_post_type_archive( '[custom_post_type_name]' )
            ||
            is_tax( '[custom_taxonomy_name]' )
        )
        &&
        !is_user_logged_in()
    ) {
        wp_redirect( get_home_url() );
        exit;
    }
    return $content;
}

Essentially, this runs three early checks:

  1. Does the $post object’s post type match what you’re trying to hide?
  2. Is this URL a post type archive for the post type you’re trying to hide?
  3. Is this URL a taxonomy/term page for the taxonomy you’re trying to hide?

If any of these is a match and the user is not logged in, then the user is redirected to the site’s homepage.