I recently worked on a website project where the client wanted to move a temporary development site on a subdomain to a new top level site. After launching the new site I discovered the client shared the temporary site URL with clients. The result was some clients were using the development site to place orders even after the new site was launched.
Once I realized this happened it was a complicated problem to fix. Exporting WooCommerce orders and customers and importing them to the new site is not a simple matter. Because the new site already had orders it was too late to migrate the site again.
The simple solution was to fulfill the orders on the development site, then duplicate any customers and orders on the new site. In addition, it was necessary to send users from the development site to the new site so they wouldn’t continue using the development site. The client still needed access to the dashboard (/wp-admin/) to fill and complete the orders placed on the test site.
To prevent customers from browsing the development site, while allowing the client to access the dashboard, I added the following code to the development site:
<?php
if ( ! is_admin() ) {
wp_redirect( 'https://new-site.com' . $_SERVER['REQUEST_URI'], 301 );
exit;
}
This code can be placed in a theme’s functions.php file so it will be executed every time a page is requested on the site. It will send any requests on old website to the corresponding location on the new domain (new-site.com in this example), except for requests for the admin dashboard. The . $_SERVER[‘REQUEST_URI’] portion sends the current request to the new site, so the user will get the corresponding page on the new site. The 301 at the end is a permanent redirect. This tells search engines to update any old pages indexed with their new location. It also causes visitors’ browsers to cache the redirect. If there is any chance this redirect might change in the future, use a 302 temporary redirect instead. In this case, the move is permanent, so a 301 is used.
When adding code to a website it is not recommended to edit the theme directly. Typically a website would use a child theme that inherits everything from the parent, so that the parent theme can be updated while keeping the changes defined in the child theme. But child themes aren’t always a good solution, especially when working on a website that is already developed.
For adding code like the above, rather than edit functions.php, I use WPCode’s WordPress Code Snippets Plugin. I use this plugin frequently for adding PHP code and CSS.