Home > Dev > WordPress SEO > 301 Redirects for SEO

301 Redirects for SEO

This code handles 301 redirects to maintain SEO value when URLs change.

// Add this to your theme's functions.php file

function handle_301_redirects() {
    $redirects = array(
        '/old-page/' => '/new-page/',
        '/old-page-2/' => '/new-page-2/'
    );

    $request_uri = $_SERVER['REQUEST_URI'];
    foreach ($redirects as $old_url => $new_url) {
        if ($request_uri === $old_url) {
            wp_redirect($new_url, 301);
            exit;
        }
    }
}
add_action('init', 'handle_301_redirects');
Back