I have a form that redirects and opens a "thank you" page on submission, but I would like no one to have access to this page by URL. This page should be accessible from the redirection of the form. The problem is that I tried to do it from .htaccess
, but it does not work.
Current URL: mySite.com/thank-you
I would like to mask it as: mySite.com/
I used this code in function.php:
/**
* Form ---> Thank you page
*
*/
add_action( 'wp_footer', 'mycustom_wp_footer' );
function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '6881' == event.detail.contactFormId ) { // Sends sumissions on form idform to the thank you page
location = '/thank-you/';
} else { // Sends submissions on all unaccounted for forms to the third thank you page
// Do nothing
}
}, false );
</script>
<?php
}
I don't know how to make it possible. Can someone help me please?
One way to prevent direct access to your "Thank You" page is by making sure that the people who get there actually came from your "Contact Us" page.
Try adding this to your theme's functions.php
file, read the comments for details:
/**
* Redirects user to homepage if they try to
* access our Thank You page directly.
*/
function thank_you_page_redirect() {
$contact_page_ID = 22; // Change this to your "Contact" page ID
$thank_you_page_ID = 2; // Change this to your "Thank You" page ID
if ( is_page($thank_you_page_ID) ) {
$referer = wp_get_referer();
$allowed_referer_url = get_permalink( $contact_page_ID );
// Referer isn't set or it isn't our "Contact" page
// so let's redirect the visitor to our homepage
if ( $referer != $allowed_referer_url ) {
wp_safe_redirect( get_home_url() );
}
}
}
add_action( 'template_redirect', 'thank_you_page_redirect' );
Update:
Alternatively, this JavaScript version achieves the same result (which should be more compatible with caching plugins):
function mycustom_wp_head() {
$home_url = get_home_url();
$contact_page_ID = 22; // Change this to your "Contact" page ID
$thank_you_page_ID = 2; // Change this to your "Thank You" page ID
if ( is_page($thank_you_page_ID) ) :
?>
<script>
var allowed_referer_url = '<?php echo get_permalink( $contact_page_ID ); ?>';
// No referer, or referer isn't our Contact page,
// redirect to homepage
if ( ! document.referrer || allowed_referer_url != document.referrer ) {
window.location = '<?php echo $home_url; ?>';
}
</script>
<?php
endif;
}
add_action( 'wp_head', 'mycustom_wp_head' );