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 ), "https://wordpress.stackexchange.com/" );
// 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.. 🙂