Masking WordPress Logout Functionality w/ a Custom URL

Masking WordPress Logout Functionality w/ a Custom URL

Imagine a scenario where you would like to provide an on-the-fly logout link to the users of your WordPress site. It might be because the login link of your site is blocked through a firewall or you might want to create a custom logout URL to hide that your site is driven by WordPress.

As the login and logout link go through the same wp-login.php path in WordPress, users won’t find a way to log out of your site if the login link is locked up or blocked for any other reasons.

In this tutorial, you will learn to apply logout functionality to a custom URL that can log out a user on the fly, and later we’ll use the logout URL as a replacement for the default logout URL.

Masking WordPress Logout Functionality

Let’s create a logout URL for your WordPress site that can perform logout functionality on the fly. Let’s say the URL is example.com/?logout=1 which will log out a user on click.

Add the code snippet to your WordPress site to create a logout functionality for the link:

// Apply WordPress logout functionality to a link
add_action( 'wp_loaded', 'bydik_custom_logout_action_url' );
function bydik_custom_logout_action_url() {
    if ( ! isset ( $_GET['logout'] ) ) return;
    wp_logout();
    $loc = isset ( $_GET['redirect_to'] ) ? $_GET['redirect_to'] : home_url( '/' );
    wp_redirect( $loc );
    exit;
}

That’s it! You can now provide the logout URL where you want and this will log out a user on click just like the default WordPress logout link. All your problems are solved at once!

Quick link:
Change Default WordPress Logout URL to a Custom URL

Want to apply the new URL everywhere? Add the custom function to show it everywhere where WordPress comes up with the logout URL to log out a user from your site:

// Replace WordPres logout URL output everywhere
add_filter( 'logout_url', 'bydik_custom_logout_url_output', 10, 1 );
function bydik_custom_logout_url_output( $logout_url, $redirect ) {
    $url = add_query_arg( 'logout', 1, home_url( '/' ) );
    if ( ! empty ( $redirect ) ) $url = add_query_arg( 'redirect_to', $redirect, $url );
    return $url;
}

Adding code snippets for the first time? Don’t know where and how to add code snippets to WordPress? We have an in-depth article on how to add code snippets to a WordPress site.

Like this? Share this tutorial far and wide! Have a different solution or want something to say about masking WordPress logout functionality? Let us know in the comments.

Leave a Reply

Your email address will not be published. Your comments must follow our guidelines.