# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: private, login, 404
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/private-posts-redirect-to-login/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Send Visitors to Login for Private Posts" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
