how to prevent/block direct access to a thank you page, only access if redirected from submiiting a form (in a different page)?
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
If the form is redirecting from one page only, you can easily use wp_get_referer() to check for it and if not, redirect.
add_action('template_redirect', function() {
// ID of the thank you page
if (!is_page(12345)) {
return;
}
// coming from the form, so all is fine
if (wp_get_referer() === 'URL_OF_FORM') {
return;
}
// we are on thank you page
// visitor is not coming from form
// so redirect to home
wp_redirect(get_home_url());
exit;
} );
Method 2
Don’t know why the above code don’t work for me. However the below code worked perfectly.
<?php
function thank_you_rd(){
if ( ! is_page('thank-you')) {
return;
}
if (wp_get_referer() == '/contact-us/') {
return;
}
wp_redirect( get_home_url() );
}
add_action('template_redirect', 'thank_you_rd');
?>
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