Question:
I have a WordPress website with pages that require people to log in. To make this possible I have installed the free Ultimate Member plugin. The disadvantage is that users then have to log in with a username / email address and password which is experienced as annoying.
Therefore, I also installed the Magic Login plugin. Users enter their email address and they will receive a unique login link via email. This way of logging in is being used in more and more places.
> Also read “Logging into WordPress with a one-time link” (Dutch)
The disadvantage of the Magic Login link is that it does not return the user to the page that required login. This would be handy, though. Otherwise, people have to click on the previous button or look up the page again.
But how to return a user after login?
Answer:
The Magic Link shortcode to display the login form provides support for a redirect_to=”” parameter. But by default you can only provide a static URL such as a the my personal page or the homepage.
We want to set the value for this parameter dynamically because there are multiple pages that require login. The preference is not to modify the Magic Login plugin because after a plugin update you lose the changes.
Add the PHP code below to your theme’s functions.php file:
function custom_magic_login_form() { if (false !== wp_get_referer()) { $html = do_shortcode('[magic_login_form redirect_to="' . esc_url_raw(wp_get_referer()) . '"]'); } else { $html = do_shortcode('[magic_login_form]'); } echo $html; } add_shortcode('custom_magic_login_form', 'custom_magic_login_form');
Explanation:
The above PHP function executes the shortcode of the Magic Link plugin to display the login form. But if the referrer is known, it is added to the redirect_to=”” parameter.
A referrer is the URL from which a user was redirected to the login form because the user is not logged in yet. That is exactly the URL we want to redirect the user back to after logging in.