0

I have the following code running in the Code Snippets plugin, which works the way I need it to work for the most part. Basically I have the Elementor login form in a popup on my website, that way, a user can login from any page on the website. At present, the code checks to see if the login was successful, and if not, it adds ?login=failed to the URL, which is what I want it to do. The issue I am having is, it keeps redirecting to the home page, instead of the current page that I am on. For example if I try to login while on the gallery page (https://example.com/gallery/) and there is a login error, I will be redirected back to the home page (https://example.com/?login=failed) instead of (https://example.com/gallery/?login=failed). This is the furthest I was able to get before getting stuck. Basically, any page/archive/taxonomy I am on, if I login and there's an error, I need that page/archive/taxonomy to be refreshed and ?login=failed appended to the URL. And on the same token, if the login is successful, refresh the page and remove the ?login=failed parameter.

// Add hook to redirect the user back to the Elementor login page if the login failed
add_action('wp_login_failed', 'elementor_form_login_fail', 10, 1);

function elementor_form_login_fail($username) {
    $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

    if (!empty($referrer) && !strstr($referrer, 'wp-login') && !strstr($referrer, 'wp-admin')) {
        // Redirect back to the referrer page, appending the login=failed parameter and removing any previous query strings
        wp_redirect(add_query_arg('login', 'failed', remove_query_arg('login', $referrer)));
        exit;
    }
}

// Add hook to remove ?login=failed from URL after successful login
add_action('wp_login', 'remove_login_failed_redirect', 10, 2);

function remove_login_failed_redirect($user_login, $user) {
    // Check if the login was successful
    if (!is_wp_error($user)) {
        $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

        // Check if the referrer contains ?login=failed
        if (strpos($referrer, '?login=failed') !== false) {
            // Remove the login=failed parameter from the URL
            $redirect_url = remove_query_arg('login', $referrer);
            
            // Redirect back to the updated URL
            wp_redirect($redirect_url);
            exit;
        }
    }
}

0

Browse other questions tagged or ask your own question.