Redirect Old domain & posts to new domain homepage

There are many useful threads on StackOverflow on how implement this, but here’s a small WP solution that you can apply without modifying your .htaccess file:

add_action('init', function() {

    $redirect_to_domain = 'google.com'; // without protocol
    $https = false; // redirect to https ( default: http )

    // don't change the following unless you know what you're doing
    $domain = str_replace( array('http://', 'https://'), '', get_site_url() );
    $uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

    wp_redirect( ( $https ? "https://" : "http://" ) . str_replace( $domain, $redirect_to_domain, $uri ) );
    exit;

});

Remember, WordPress will still be initiated until the redirect is performed.

Hope this helps.

Leave a Comment