1

So I have the code below in my functions.php file. It works for logged out users but it also redirects users that are logged in. Can anyone help?

add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
    if ( is_paged() || is_author() || is_single()  && ! is_user_logged_in() ) {
        wp_redirect( 'http://www.exampleblog.net/members-only/', 301 );
        exit;
    }
}

I'm using this to redirect all logged out users to a page where it tells them they have to be logged in to view other pages (Pages 2, 3 and so on. Also for them not to view author's page and archives when they click authors name).

4

You need to wrap the first three || conditions in additional parentheses so they are evaluated first BEFORE the last && condition:

Psuedocode example:

    here                               here 
     ↓                                  ↓  
if ( (condition || condtion || condition) && ! condition ) {
    //do business logic...
}

This now means that:

If any ONE of is_paged() OR is_author() OR is_single() IS true THEN evaluate the second condition ! is_user_logged_in()

In your original code:

With no additional parentheses wrapping the first three conditions, IF any of those four conditions return true then you would redirect your user whether they are logged in or not.

Final code with additional parentheses:

add_action( 'template_redirect', 'redirect_to_specific_page' );

function redirect_to_specific_page() {   
    if ( (is_paged() || is_author() || is_single()) && ! is_user_logged_in() ) {
        wp_redirect( 'http://www.exampleblog.net/members-only/', 301 ); exit; 
    } 
}
  • @ineedhelp Good to hear, feel free to mark this answer as correct/complete. – userabuser Jul 24 '15 at 2:17

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.