301 redirects can be set up if you want to permanently redirect viewers from one website page to another. This can be necessary or beneficial if you have redesigned your website and changed some URLs, migrated your site, transferred your site to HTTPS or SSL, or changed your permalink or slug structure. With a 301 redirect, you can avoid those annoying static “Page Not Found” messages, and make sure your visitors are transferred to your actual site or page. Setting up 301 redirects can be done in several ways for a WordPress site, namely through WordPress plugins, by editing the .htaccess file or through PHP modifications. Because plugins usually come with their own instructions, we’re focussing on how to set up a 301 redirect via other means.
Step by step setup of WordPress 301 redirects with PHP
You can manually code your 301 redirects into the PHP of your WordPress theme if you prefer not to use a plugin or alter your .htaccess files. You could add this code directly into the header.php file, but it’s recommended to place it into the functions.php file and use a WordPress hook. This way all your modifications are in one place and you’re not affecting core files. Make sure you are making these changes in a child theme so as to not lose them after an update.
- Access your admin control panel.
- Select Appearance -> Editor. The right side of the screen offers the files you can edit. Select Theme Functions (functions.php).
- Insert your code snippet at the bottom of the file. The WordPress PHP code for redirects should look like this:
wp_redirect( ‘http://mysite.com/mynewpost’, 301 );
- Click Update File to save changes.
- Visit the old page to check that the redirect is functioning correctly.
Send your visitors to the right site
301 redirects in WordPress also help transfer your old page’s SEO and backlinks to your new page. This way you are keeping your visitors and your statistics. Using PHP coding for a 301 redirect is an advanced method. Remember that the code in functions.php apply to every page, so if you only want to redirect a specific URL, you’ll need to wrap the redirect in a conditional requirement. Make sure to refresh your browser cache or use an HTTP status code checker to confirm your redirect is functioning. Contact Cloud.co.za for more advice on how to setup 301 redirects on WordPress.