Projects Engine - Word

template_redirect

template_redirect is a WordPress hook that gets triggered just before WordPress determines which template file to load.

Home / Dictionary / template_redirect

template_redirect is a WordPress hook that gets triggered just before WordPress determines which template file to load. It’s useful for cases where you want to override which template file is used or even redirect to a completely different URL before the actual template rendering occurs.

Common Use Cases:

  1. Conditional Template Loading: You can check certain conditions (like post type, user role, etc.) and then load a different template file or redirect to another page.
  2. Custom Redirections: If you want to redirect users based on specific logic (like if a user is not logged in), you can perform the redirect using this hook.

Example of Redirecting a User to Another Page:

add_action('template_redirect', 'custom_redirect_logic');
function custom_redirect_logic() {
    if ( is_page('about') && !is_user_logged_in() ) {
        wp_redirect( home_url('/login') );
        exit;
    }
}

Explanation:

  • is_page(‘about’): Checks if the current page is the “About” page.
  • !is_user_logged_in(): Checks if the user is not logged in.
  • wp_redirect(): Redirects the user to the login page.
  • exit: Ensures that no further processing happens after the redirection.

This hook should not be used for enqueueing scripts or styles, as it’s primarily intended for modifying or redirecting templates.