Send Visitors to Login for Private Posts
When a logged-out visitor opens a private post or page, they are sent to the login screen and back again, instead of seeing a "not found" error.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
global $wp_query;
if ( ! is_404() || is_user_logged_in() ) {
return;
}
$id = (int) $wp_query->get( 'p' ) ? (int) $wp_query->get( 'p' ) : (int) $wp_query->get( 'page_id' );
$post = $id ? get_post( $id ) : null;
if ( ! $post ) {
$name = $wp_query->get( 'pagename' ) ? $wp_query->get( 'pagename' ) : $wp_query->get( 'name' );
$post = $name ? get_page_by_path( $name, OBJECT, array_values( get_post_types( array( 'public' => true ) ) ) ) : null;
}
if ( $post && 'private' === $post->post_status ) {
wp_safe_redirect( wp_login_url( get_permalink( $post ) ) );
exit;
}
} );
Notes
After logging in, users who are not allowed to read private content still see the 404 page.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.