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.