Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

mayeenulislam commented Oct 8, 2018

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
You can’t perform that action at this time.