do_action( 'template_redirect' )

Fires before determining which template to load.


More Information More Information

  • This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.
  • Loading a different template is not a good use of this action hook. If you include another template and then use exit() (or die()), no subsequent template_redirect hooks will be run, which could break the site’s functionality. Instead, use the template_include filter hook to return the path to the new template you want to use. This will allow an alternative template to be used without interfering with the WordPress loading process.

Top ↑

Source Source

File: wp-includes/template-loader.php

View on Trac


Top ↑

Changelog Changelog

Changelog
Version Description
1.5.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Rami Yushuvaev

    Redirect existing pages to other pages:

    function custom_redirects() {
    
    	if ( is_front_page() ) {
    		wp_redirect( home_url( '/dashboard/' ) );
    		die;
    	}
    
    	if ( is_page('contact') ) {
    		wp_redirect( home_url( '/new-contact/' ) );
    		die;
    	}
    
    }
    add_action( 'template_redirect', 'custom_redirects' );
    
  2. Skip to note 2 content
    Contributed by Andrew Lima

    If you need to remove a template_redirect from within a custom plugin, simply using remove_action( 'template_redirect', 'function_to_remove' ); won’t cut it.

    As a workaround, what you can do is create a function to hook into template_redirect action earlier and then remove the redirect you are trying to remove.

    // remove a template redirect from within a custom plugin.
    add_action( 'template_redirect', 'remove_my_action', 5 );
    function remove_my_action(){
        remove_action('template_redirect', 'function_to_remove', 10 );
    }
    
  3. Skip to note 3 content
    Contributed by stevenlinx

    Example migrated from Codex:

    Following example will redirect all non-authenticated users to a custom ‘signup’ page when trying to visit the ‘goodies’ page.

    function my_page_template_redirect() {
        if ( is_page( 'goodies' ) && ! is_user_logged_in() ) {
            wp_redirect( home_url( '/signup/' ) );
            exit();
        }
    }
    add_action( 'template_redirect', 'my_page_template_redirect' );
    

    Don’t forget to call exit() ( or die() ) after a wp_redirect().

You must log in before being able to contribute a note or feedback.