Redirect wordpress back to referring page after login

Sometimes you have a situation where you want the customer to log in, like a donation page, but you don’t want them to end up at /my-account/ but rather be taken back to the page where they were when they started.

This code is useful for donation sites, as well as refer a friend scenarios.

<?php

if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
    add_filter('login_redirect', 'my_login_redirect', 10, 3);
    function my_login_redirect() {
        $location = $_SERVER['HTTP_REFERER'];
        wp_safe_redirect($location);
        exit();
    }
}
Click to Copy