How to access the thank you page from the single post?
-
22-04-2021 - |
Pregunta
I have a thank you page on my website and I don't want anyone can access it directly so I use the below code and it working.
add_action('template_redirect', function() {
// ID of the thank you page
if (!is_page(947)) { //id of page
return;
}
// coming from the form, so all is fine
if (wp_get_referer() === get_site_url().'/contact-us/') {
return;
}
// we are on thank you page
// visitor is not coming from form
// so redirect to home
wp_redirect(get_home_url());
exit;
});
Now, what I am doing, I have one more form on my single post and once the user submits the form then it will redirect to the thank you page but it's not going because I added the above code on my function.php
.
So anyone knows how to access the thank you page from the single post?
Solución
Note: WordPress deliberately misspelled the word 'referer', and thus, so did I..
If you just want to check if the referer is your contact-us
Page or any single Post page, then you can first retrieve the current URL path (i.e. example.com/<this part>/
) and then check if the path is exactly contact-us
(or whatever is your contact Page's slug), and use get_posts()
to find a single post having that path as the slug.
So try this, which worked for me (tested with WordPress 5.6.1):
// Replace this:
if (wp_get_referer() === get_site_url().'/contact-us/') {
return;
}
// with this:
$path = trim( parse_url( wp_get_referer(), PHP_URL_PATH ), '/' );
// If it's the contact page, don't redirect.
if ( 'contact-us' === $path ) {
return;
} elseif ( $path ) {
$posts = get_posts( array(
'name' => $path,
'posts_per_page' => 1,
) );
// If a post with the slug in $path was found, don't redirect.
if ( ! empty( $posts ) ) {
return;
}
}
- But note that the code would only work if your permalink structure (for the default
post
type) is/%postname%/
— with or without the leading and/or trailing slashes.
And bear in mind that the referer can be easily spoofed, so you might want to consider a more reliable approach like using transients or nonces with a short lifespan.. :)
Otros consejos
It might be better to match the thanks page, then try to match the referer and if those conditions don't match, do nothing.
add_action('template_redirect', function() {
// match based on two condition:
// current page is "thanks" - which I am guessing is "thanks"
// and the referer is /contact-us/ - not this is unreliable, as referer might be empty
if (
is_page('thanks') // is page "thanks"
) {
// referer matches
if( wp_get_referer() === get_site_url().'/contact-us/' ) {
error_log( 'All good..' );
return;
} else {
// redirect to home
wp_redirect( get_home_url() );
exit;
}
}
// nothing to do here, as not thanks page
});