The template_redirect
hook is a powerful tool in the WordPress developer toolkit. It allows developers to intercept the template loading process and redirect it to a custom template or content. This means that when a particular URL is requested, the developer can use the template_redirect
hook to determine which template or content is loaded in response.
The template_redirect
hook is used to modify the normal template loading process and redirect WordPress to a different template or content. This can be used to create custom pages or content for a specific URL, or to modify the behavior of existing templates.
For example, let’s say you have a custom post type called "books" and you want to redirect all requests to the single book page to a custom template. You can use the template_redirect
hook to intercept the request and load a custom template instead of the default single book template.
function my_custom_book_template_redirect() {
if ( is_singular( 'books' ) ) {
// Load custom single book template
include( get_template_directory() . '/single-books.php' );
exit;
}
}
add_action( 'template_redirect', 'my_custom_book_template_redirect' );
In this example, we have created a function called my_custom_book_template_redirect()
that checks if the current request is for a singular "books" post. If it is, we load a custom template called single-books.php
and exit the script to prevent any further template loading.
Overall, the template_redirect
hook is a powerful tool for developers to create custom templates and content for specific URL requests. It can be used to modify the behavior of existing templates or create entirely new ones.
WordPress snippets using the template_redirect hook
-
Redirect all 404 to homepage
-
How to Rewrite the Search Results Slug for a Specific Search Term in WordPress
-
How to Restrict User Access to Specific Templates in WordPress
-
How to Redirect to a Post When Search Query Returns a Single Result in WordPress
-
How to Redirect Users to the Most Recent Post in WordPress
-
How to Automatically Redirect to a Single Post in WordPress if Only One Post Exists in a Category or Tag
-
How to Redirect Your WordPress Home Page to Your First Blog Post