Home / eCommerce / WWLC – Route logout through home URL to prevent exposing the hidden login path
Duplicate Snippet

Embed Snippet on Your Site

WWLC – Route logout through home URL to prevent exposing the hidden login path

Code Preview
php
<?php
/**
 * Route logout through home URL to prevent exposing the hidden login path.
 */
add_filter( 'logout_url', function ( $logout_url, $redirect ) {
    $redirect_to = $redirect ?: home_url( '/' );
    return add_query_arg(
        [
            'do_logout'   => '1',
            '_wpnonce'    => wp_create_nonce( 'safe-logout' ),
            'redirect_to' => rawurlencode( $redirect_to ),
        ],
        home_url( '/' )
    );
}, 10, 2 );
add_action( 'init', function () {
    if ( empty( $_GET['do_logout'] ) ) {
        return;
    }
    if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'safe-logout' ) ) {
        wp_die( 'Security check failed.' );
    }
    $redirect = ! empty( $_GET['redirect_to'] )
        ? esc_url_raw( wp_unslash( $_GET['redirect_to'] ) )
        : home_url( '/' );
    wp_logout();
    wp_safe_redirect( $redirect );
    exit;
} );

Comments

Add a Comment