Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

template_redirect

Fires on the front end once WordPress knows what's being viewed, before a template loads. Ideal for redirects and access checks.

  • Type Action
  • From WordPress
  • Since 1.5.0
  • Fired in wp-includes/template-loader.php

When it fires

template_redirect runs on front-end page loads only, after the main query has run and before WordPress picks a template file. Conditional tags like is_page(), is_singular() and is_404() all work, and no HTML has been sent, so you can still redirect or set headers.

It doesn't run in the admin area, for AJAX calls or for REST API requests.

Parameters

None. Your callback takes no arguments.

Example: Send logged-out visitors from a members page to the login screen

PHP
add_action( 'template_redirect', function () {
	if ( is_page( 'members' ) && ! is_user_logged_in() ) {
		wp_safe_redirect( wp_login_url( get_permalink() ) );
		exit;
	}
} );

Good to know

  • Always call exit after wp_safe_redirect() or wp_redirect(), otherwise the page carries on loading.
  • Don't use this hook to load a different template. The template_include filter is made for that.
  • Page caching can serve a stored copy without running PHP at all. Exclude protected pages from the cache so the check always runs.

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.