The question:
how to prevent/block direct access to a thank you page, only access if redirected from submiiting a form (in a different page)?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
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