To change the default WordPress admin URL to a different address for security purposes, you can use the following code snippet.
Please note: Changing the default admin URL can enhance security, but it’s essential to proceed with caution as any mistake could lock you out of your WordPress site. Make sure to backup your website before making any changes.
// Define a new admin URL
define('WP_ADMIN_DIR', 'new_admin_url');
define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . WP_ADMIN_DIR);
// Set the location of the wp-admin directory
define('ADMIN_COOKIE_PATH', '/' . WP_ADMIN_DIR);
// Force SSL for the new admin URL
define('FORCE_SSL_ADMIN', true);
// Redirect users accessing the old admin URL to the new one
add_action('init', 'redirect_to_new_admin_url');
function redirect_to_new_admin_url() {
if (strpos($_SERVER['REQUEST_URI'], '/wp-admin') !== false) {
wp_redirect(site_url('/' . WP_ADMIN_DIR));
exit();
}
}
// Change the login URL
add_filter('site_url', 'change_login_url', 10, 4);
function change_login_url($url, $path, $orig_scheme, $blog_id) {
$old = array('/(wp-login\.php)/');
$new = array(WP_ADMIN_DIR . '/wp-login.php');
return preg_replace($old, $new, $url, 1);
}
// Change the logout URL
add_filter('logout_url', 'change_logout_url');
function change_logout_url($url) {
return str_replace('wp-login.php', WP_ADMIN_DIR . '/wp-login.php', $url);
}
Replace 'new_admin_url'
with your desired admin URL slug.
Add the above code to your theme’s functions.php
file, or preferably in a custom functionality plugin.
After adding the code, make sure to log in using your new admin URL.