Proper Use of template_redirect Action in WordPress

template_redirect is a powerful hook available in WordPress, however a common misconception is: you can use it to load a different template. This is NOT the proper use of this hook! Use the template_include filter if you want to change the template file.

template_redirect is good action to leverage when you need to redirect users elsewhere after WordPress has made it's main query and all objects are available. However, since no output has been sent to the browser (ie. headers) at this point it provides a lot of flexibility.

Below is an example of how WordPress's template_redirect action could be used.

/**
 * Disables 'Sample Report' post type archive and single for non-auth'd users
 */
function disable_sample_reports(){
  global $wp_query;

  $post_types = array( 'sample_report' );

  if( ! is_user_logged_in() && in_array( $wp_query->query_vars['post_type'], $post_types ) ){

    if( is_archive() || is_single() ){
      // Redirect home
      wp_redirect( esc_url( home_url() ) );
      exit();
    }
  }
}
add_action( 'template_redirect', 'disable_sample_reports', 1 );