template_include
Your first option here is to change the template that is used your pages so that you can do anything you wish, once that template has been called.
The example below checks that the page is called ‘portfolio’, but obviously you can insert your own checks, and then locates a template called ‘my-template-page.php’. If that template doesn’t exist you are just shown the original template.
add_filter( 'template_include', 'my_custom_page_template', 99 );
function my_custom_page_template( $template ) {
if ( is_page( 'portfolio' ) ) {
$new_template = locate_template( array( 'my-template-page.php' ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
template_redirect
You can also redirect the user to another page, again allowing you to do anything that you want but this time with the added bonus of being able to change the URL. Personally I’ve only every used this hook when I’m forcing people to log in before viewing a page and would suggest templage_include
, but if you have your reasons then fair enough.
In conjunction with this code you would need a template page-my-template-example.php
as well as a page called ‘My Template Example’.
add_action( 'template_redirect', 'my_redirect_to_template_page' );
function my_redirect_to_template_page(){
if( is_page( 'goodies' ) ) {
wp_redirect( home_url( '/my-template-page/' ) );
exit();
}
}