I have a menu item “Checkout”. When clicked it links to the login popup prompting users to register/login/continue as guest and from there to checkout.
How can I make that same button redirect to the checkout page if a user is already logged in?
Using ELementor and Astra theme
Thanks!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In a more “vanilla” setting (i.e. without a page builder and not using a modal or popup) you would have two basic approaches:
- a) generating a different menu
- b) redirecting from the target page
I would not generate a different menu because, in my experience, it seems a little more messy and less performant depending on the server and WordPress settings. I would use option B and I would not use the login in a popup/modal, using a function along the lines of the code you shared, but with a few tweaks:
add_action( 'template_redirect', 'wpse381189_dashboard_redirect' );
function wpse381189_dashboard_redirect() {
// make sure i) we are not in admin side ii) we are not doing ajax iii) user is logged in.
if( !is_admin() && !defined( 'DOING_AJAX' )&& is_user_logged_in() ) {
nocache_headers();
wp_safe_redirect( home_url( '/dashboard/' ) );
exit();
}
}
If you still want to use a popup/modal, you would need to use a function that returns data telling the frontend the user status (i.e. logged in or logged out) and let the Javascript handle the redirection. But this might be a little bit difficult because you are using a non-core page builder, Elementor, which is off-topic in this community and depending on the template you using, make most of WordPress core hooks unavailable. In this case recommend you take a look at Using Ajax articles on WordPress official documentation and then find in the page builder documentation how to handle Ajax and add your own scripts to it.
Method 2
Probably somethin like this, but I don’t know how to adapt it top my case:
add_action( ‘template_redirect’, ‘dashboard_redirect’ );
function dashboard_redirect()
{
if( is_page( home_url( ‘/min-konto/’ ) ) && ! is_user_logged_in() )
{
wp_redirect( home_url( ‘/dashboard/’ ) );
exit();
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0