To create a redirect function in WordPress from old URLs to new ones, you can use the .htaccess
file or write custom code in the theme’s functions.php
file. Let’s look at both options:
1. Redirect via .htaccess
If you need to implement redirects for multiple old URLs, it’s easiest to do it through the .htaccess
file in the root of your site. Open or create the .htaccess
file and add the redirect rules.
Example of a redirect from an old URL to a new one:
Redirect 301 /old-url/ https://example.com/new-url/
If you need to add multiple redirects, just append them to the file:
Redirect 301 /old-url-1/ https://example.com/new-url-1/
Redirect 301 /old-url-2/ https://example.com/new-url-2/
2. Redirect via functions.php
If you’d like to implement redirects at the code level in WordPress, you can add a function to your theme’s functions.php
file. Here’s an example function:
function custom_redirects() {
if (is_page('old-page')) {
wp_redirect('https://example.com/new-page', 301);
exit;
}
// Example for multiple old URLs
if (is_page('old-page-2')) {
wp_redirect('https://example.com/new-page-2', 301);
exit;
}
}
add_action('template_redirect', 'custom_redirects');
This code uses is_page('old-page')
to check if the current page is an old URL and, if so, performs a 301 redirect to the new URL.
3. Using a Plugin
If you prefer to manage redirects through a plugin, you can install plugins like Redirection or Simple 301 Redirects, which allow you to manage redirects via the WordPress admin interface.
The method you choose depends on the number of redirects, your level of control, and your preference for managing the site’s code.