Skip to content

Instantly share code, notes, and snippets.

@yanceyk

yanceyk/functions.php

Last active Dec 10, 2020
Embed
What would you like to do?
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