Last active
December 10, 2020 15:22
-
-
Save yanceyk/34dc0f6e2e92b5044a0b1ec91cf150d6 to your computer and use it in GitHub Desktop.
Prevent direct access via URL to a WordPress page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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