gomez
gomez

Reputation: 85

How hide page if user not logged in Wordpress

When a user, who is not logged, in enters to mysite.com/cabinet the view includes cabinet details. How do I hide current page if a user is not logged in and redirect to home page. I used this code, but not working.

if (!is_user_logged_in() && is_page('cabinet') ) {
    wp_redirect( 'http://www.example.dev/page/' ); 
}

*cabinet - page-cabinet.php

Upvotes: 1

Views: 3068

Answers (2)

Mahfuzul Hasan
Mahfuzul Hasan

Reputation: 172

Maybe you are getting "Warning: Cannot modify header information - headers already sent" error if you using your code in the template file.

Try this:

function mh_check_loggedin_redirect()
{
    if( is_page( 'cabinet' ) && ! is_user_logged_in() )
    {
        wp_redirect( home_url() );
        die;
    }
}
add_action( 'template_redirect', 'mh_check_loggedin_redirect' );

Note: Add this code in the functions.php file

Upvotes: 3

dineshkashera
dineshkashera

Reputation: 1502

You can redirect by using template_redirect action hook

function my_page_template_redirect()
{
    if (!is_user_logged_in() && is_page(YOUR_PAGE_ID) ) {
    {
        wp_redirect( 'http://www.example.dev/page/' ); 
        die;
    }

   if(is_user_logged_in() && is_page(YOUR_PAGE_ID) ) {
   {
        wp_redirect( site_url() ); 
        die;
   }
}
add_action( 'template_redirect', 'my_page_template_redirect' );

*Note : Replace YOUR_PAGE_ID with your page id.

For more help : Click Here

Upvotes: 0

Related Questions