template_redirect
Fires before WordPress determines which template file to use to display the content.
The event is convenient for redirects because WordPress has processed the main query and set up all objects ($wp_query, $post, and conditional tags), but content has not yet been output.
This is a popular hook and the most convenient place when a redirect decision requires all data about the current request (the WordPress object being handled).
A note about incorrect use of the hook
This hook must not be used to load an alternative template file. Example of incorrect code:
// Incorrect code; use the template_include hook.
add_action( 'template_redirect', 'my_callback' );
function my_callback() {
if ( /* Condition */ ) {
include( SOME_PATH . '/some-custom-file.php' );
exit();
}
}
The problem is that when the condition is true and the specified file is included, WordPress execution stops completely. Some important filters and functions used by WordPress plugins do not run before it stops. This often causes undesirable consequences that may not be immediately apparent.
Use the template_include filter to load an alternative template file:
add_filter( 'template_include', 'my_callback' );
function my_callback( $original_template ) {
if ( /* Condition */ )
return SOME_PATH . '/some-custom-file.php';
else
return $original_template;
}
The effect is the same without causing problems for plugins or other code.
In short:
template_redirect— for redirects.template_include— for including templates.
Usage
add_action( 'template_redirect', 'wp_kama_template_redirect_action' );
/**
* Function for `template_redirect` action-hook.
*
* @return void
*/
function wp_kama_template_redirect_action(){
// action...
}
Examples
#1 Redirect to the registration page
Suppose there is a service page that should be accessible only to logged-in users, while everyone else should be redirected to the registration page.
The following code demonstrates how to do this:
add_action( 'template_redirect', 'my_page_template_redirect' );
function my_page_template_redirect(){
if( is_page('service') && ! is_user_logged_in() ){
wp_redirect( home_url( '/signup/' ) );
exit();
}
}
#2 More examples
See the article Redirect to a random post in WordPress.
Changelog
| Since 1.5.0 | Introduced. |
Where the hook is called
do_action( 'template_redirect' );
Where the hook is used in WordPress
add_action( 'template_redirect', array( $this, 'handle_render_partials_request' ) );
add_action( 'template_redirect', 'rest_output_link_header', 11, 0 );
add_action( 'template_redirect', 'wp_shortlink_header', 11, 0 );
add_action( 'template_redirect', 'wp_old_slug_redirect' );
add_action( 'template_redirect', 'redirect_canonical' );
add_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
add_action( 'template_redirect', '_wp_admin_bar_init', 0 );
add_action( 'template_redirect', 'maybe_redirect_404' );
add_action( 'template_redirect', array( $this, 'render_sitemaps' ) );