0

I am using wp_redirect() to restrict access to logged out users and redirect them to login page. Here's my code which works perfecly.

function loggedout_post_redirect(){
    if ( !is_user_logged_in() && is_single() ) {
        wp_redirect( home_url() . '/login/' ) ;
        exit();
    }
}
add_action ( 'template_redirect', 'loggedout_post_redirect' );

But what if, I want to redirect all logged out users who access this specific URLs?

please note that the "www.example.com/users/" doesnt change, the only changing characters are the UserProfileA-Z. Where UserProfileA - Z is equal to the usernames of my WordPress users.

I've tried using is_page() with wild card (user/)* but it's not working.

function loggedout_user_redirect(){
    if ( !is_user_logged_in() && is_page('user/*') ) {
        wp_redirect( home_url() . '/login/' ) ;
        exit();
    }
}
add_action ( 'template_redirect', 'loggedout_user_redirect' ); 

any idea how to make this work?

0

You could make a regex if you do not use query variables from WordPress.

Here is an example:

function loggedout_user_redirect(){

    if ( ! is_user_logged_in() ) {
        $regex = '~/users/(.*)~';
        $url   = $_SERVER['REQUEST_URI'];
        
        preg_match( $regex, $url, $matches );
        
        if ( isset( $matches[1] ) && '' !== trim( $matches[1] ) ) {
            wp_redirect( site_url( '/login' ) );
            exit();
        }
    }
}
add_action ( 'template_redirect', 'loggedout_user_redirect' ); 
| improve this answer | |

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.