Skip to content

Instantly share code, notes, and snippets.

@yanceyk
Last active December 10, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanceyk/34dc0f6e2e92b5044a0b1ec91cf150d6 to your computer and use it in GitHub Desktop.
Save yanceyk/34dc0f6e2e92b5044a0b1ec91cf150d6 to your computer and use it in GitHub Desktop.
Prevent direct access via URL to a WordPress page
<?php
function prefix_no_direct_access() {
// Define Page URL for redirect.
$careers = get_permalink( get_page_by_title( 'Careers' ) );
// If this is not the Apply Now page, do nothing.
if( ! is_page( 'Apply Now' ) ) {
return;
}
// Allow direct access to logged in users who can edit pages.
if( is_user_logged_in() && current_user_can( 'edit_posts' ) ) {
return;
}
// Get the referrer from the server request.
$referer = wp_get_referer();
// If we have a referer...
if( isset( $referer ) ) {
// Parse the URL.
$refer_URL = parse_URL( $referer );
// Check for Position in the referrer path.
$position = strpos( $refer_URL[ 'path' ], 'position' );
// Verify the referer is from our site. Because, referer spoofing.
$validate_position = url_to_postid( $referer );
// If `position` is in referer path and it is from our site, do nothing. Referer is valid.
if( $position > -1 && $validate_position > 0 ) {
return;
} else { // Referer invalid, redirect.
nocache_headers();
wp_safe_redirect( $careers );
exit;
}
// Otherwise no referer, redirect.
} else {
nocache_headers();
wp_safe_redirect( $careers );
exit;
}
}
add_action( 'template_redirect', 'prefix_no_direct_access' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment