Skip to content

Instantly share code, notes, and snippets.

@Neolot
Last active May 22, 2024 21:31
Show Gist options
  • Save Neolot/5d8c72c12f5bd51f68b98e8c9e291389 to your computer and use it in GitHub Desktop.
Save Neolot/5d8c72c12f5bd51f68b98e8c9e291389 to your computer and use it in GitHub Desktop.
Wordpress. 301 redirects to another domain.
<?php
add_action( 'init', function () {
// Exceptions (do not redirect these URIs)
$exceptions = array(
'/exception1',
'/exception2',
);
// Redirects to special URIs
$special_redirects = array(
'/old-uri1' => 'https://newdomain.com/new-uri1',
'/old-uri2' => 'https://newdomain.com/new-uri2',
);
$current_uri = $_SERVER['REQUEST_URI'];
foreach ( $special_redirects as $old_path => $new_path ) {
if ( str_contains( $current_uri, $old_path ) ) {
wp_redirect( $new_path, 301 );
exit();
}
}
foreach ( $exceptions as $exception ) {
if ( str_contains( $current_uri, $exception ) ) {
return;
}
}
// Redirects to the new domain
wp_redirect( 'https://newdomain.com' . $current_uri, 301 );
exit();
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment