How to redirect non-logged in users to a specific page?

How to redirect non-logged users requesting for a specific page/URL to another page/URL and display a message like “for members only”. I know its quite easy to code using !is_user_logged_in() function but i don’t know how to code it because i am a newbie to WordPress. Care to tell me the file to put the code also.

5

Here are 2 examples which you will need to modify slightly to get it working for your specific needs.

add_action( 'admin_init', 'redirect_non_logged_users_to_specific_page' );

function redirect_non_logged_users_to_specific_page() {

if ( !is_user_logged_in() && is_page('add page slug or ID here') && $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {

wp_redirect( 'http://www.example.dev/page/' ); 
    exit;
   }
}

Put this in your child theme functions file, change the page ID or slug and the redirect url.

You could also use code like this:

add_action( 'template_redirect', 'redirect_to_specific_page' );

function redirect_to_specific_page() {

if ( is_page('slug') && ! is_user_logged_in() ) {

wp_redirect( 'http://www.example.dev/your-page/', 301 ); 
  exit;
    }
}

You can add the message directly to the page or if you want to display the message for all non logged in users, add it to the code.

http://codex.wordpress.org/Function_Reference/wp_redirect

Leave a Comment