Last active
October 8, 2018 16:11
-
-
Save stephanieleary/dfd838ef39ff72e83420b8182a0f7e3e to your computer and use it in GitHub Desktop.
Redirect private page 404 errors to the login screen with a message
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 | |
add_action( 'wp', 'my_private_page_404' ); | |
function my_private_page_404() { | |
$queried_object = get_queried_object(); | |
if ( isset( $queried_object->post_status ) && 'private' == $queried_object->post_status && !is_user_logged_in() ) { | |
wp_safe_redirect( add_query_arg( 'private', '1', wp_login_url( $_SERVER['REQUEST_URI'] ) ) ); | |
exit; | |
} | |
} | |
add_filter( 'login_message', 'my_private_page_login_message' ); | |
function my_private_page_login_message( $message ) { | |
if ( isset( $_REQUEST['private'] ) && $_REQUEST['private'] == 1 ) | |
$message .= sprintf( '<p class="message">%s</p>', __( 'The page you tried to visit is restricted. Please log in or register to continue.' ) ); | |
return $message; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm afraid, even with a hook to☹️
wp
it doesn't work. Thevar_dump($queried_object)
comesnull
for non-logged-in users.