Damian Bloemhof
Damian Bloemhof

Reputation: 11

function when user not logged in cant see page wordpress

I'm trying to add a function to Wordpress to prevent users from seeing the page if they are not logged in. I am following a youtube video and it works fine in the video but It doesn't work for me. I think it is has something to do with the is_page function.

This is my code:

add_action('template_redirect', 'members_only');
function members_only(){
    if( is_page('super-secret') && ! is_user_logged_in() ) {
        wp_redirect( home_url() );
        die();
    }

}

The page I'm on when I try to use this code is 'testproject.test/2020/09/22/super-secret'

Upvotes: 0

Views: 429

Answers (2)

Jan Muller
Jan Muller

Reputation: 41

Replace wp_redirect( home_url() ); by wp_redirect( bloginfo('url') );.

Upvotes: 1

fasstechies
fasstechies

Reputation: 109

add_action('template_redirect', 'members_only');
function members_only(){
    if( is_page('super-secret') && ! is_user_logged_in() ) {
        $url = https://www.example.com
        wp_redirect( $url);
        exit;
    }
}

Use this sample of code in functions.php but please reconfirm that (super-secret) is a correct slug of page?

Upvotes: 1

Related Questions