Skip to content

Instantly share code, notes, and snippets.

@stephanieleary
Last active October 8, 2018 16:11
Show Gist options
  • Save stephanieleary/dfd838ef39ff72e83420b8182a0f7e3e to your computer and use it in GitHub Desktop.
Save stephanieleary/dfd838ef39ff72e83420b8182a0f7e3e to your computer and use it in GitHub Desktop.
Redirect private page 404 errors to the login screen with a message
<?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;
}
@mayeenulislam
Copy link

I'm afraid, even with a hook to wp it doesn't work. The var_dump($queried_object) comes null for non-logged-in users. ☹️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment