NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Easy
Web Hosting Canada

Last modified : Sep 10 2022

Estimated reading time : 1 minute, 16 seconds - 157 words

With this tutorial, we will show you how to redirect a template page with template_redirect.

Let’s say we have a WordPress called Rank and it’s slug is rank.

Where do I find my page’s slug?

To find the page slug, open the page in question in your Admin and you’ll find the modifiable slug under the page’s title. Like in the image below:

So in this example, I want to redirect my page rank to rank-top-100:

Redirection de page WordPress en 301

In your function.php file, add the template_redirect mechanic and use the via_redirect_page function.

add_action( 'template_redirect', 'via_redirect_page' );
function via_redirect_page() {
	if ( is_page('classement') && ! is_user_logged_in() ) {
		wp_redirect( 'http://meilleurstubes.com/classement/top-100/', 301 ); 
		 exit();
	}
}

We can now test the redirect to make sure it works. Don’t forget the exit() or die() after a wp_redirect().

Just remember that the redirect will not work if you’re connected with your Admin credentials as we specified that redirects do not work when logged it. Or either log out, use a different browser or private browser.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>