I have post list page of a category. I want to redirect not logged user to login page before he views the post page. I tried with wp-members plugin, but not. In wp-members plugin, there is a hook to the_content() and it changes the content and does not redirect.

How can I solve this problem?


The determination to redirect needs to be made prior to headers being sent to the browser. Otherwise you risk PHP warnings (i.e. errors) when the page is rendered. This makes the timing of the use of wp_redirect() incorrect in the other answers. (The function is right, it's just used incorrectly.)

If you are going to redirect the user to another page, you need to hook it early enough that you can still safely redirect the user but late enough that you'd have information about the page (if you are checking what page the user is trying to view).

A simple example would be as follows:

add_action( 'template_redirect', 'my_redirect_to_login' );
function my_redirect_to_login() {
    if ( ! is_user_logged_in() ) {
        wp_redirect( wp_login_url() );

That is a generic WP example, which should work for general use. However, since you mentioned the WP-Members plugin being used, there are some API functions within WP-Members that would/could be used along with this.

The following example (taken from the plugin's documentation) demonstrates how to redirect the user to the login page if (1) the user is not logged in and (2) the current page is not the plugin's login, registration, or user profile page:

add_action( 'template_redirect', 'my_redirect_to_login' );
function my_redirect_to_login() {

  // Get an array of user pages with wpmem_user_pages()
  // @see: http://rocketgeek.com/plugins/wp-members/docs/api-functions/wpmem_user_pages/
  $pages = wpmem_user_pages();

  // If the user is not logged in, and the current page is not in the user pages array.
  // @see: http://rocketgeek.com/plugins/wp-members/docs/api-functions/wpmem_current_url/
  if ( ! is_user_logged_in() && ! in_array( wpmem_current_url(), $pages ) ) {
    // Redirect the user to the login page.

In your post list page do something like:

if (is_user_logged_in() ) {
     //show what you want to show to the logged in users    
} else {    
     //show what you want to show to the general visitors (NOT logged in)

     //and/or redirect them to the login page
     wp_redirect( wp_login_url() );

The is_user_logged_in function returns TRUE or FALSE, depending on the user’s status.

      <?php if (is_user_logged_in()) { ?>

        <p>Welcome, registered user!</p>

       <?php } else { // not logged in ?>

         <?php wp_redirect( wp_login_url() ); ?>

      <?php } ?>

i think it work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.