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?
- www.example/users/UserProfileA
- www.example/users/UserProfileB
- www.example/users/UserProfileC
- ..
- ..
- ..
- www.example/users/UserProfileZ
please note that the "www.example/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?
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?
- www.example/users/UserProfileA
- www.example/users/UserProfileB
- www.example/users/UserProfileC
- ..
- ..
- ..
- www.example/users/UserProfileZ
please note that the "www.example/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?
Share Improve this question asked Aug 6, 2020 at 7:31 Ben Michael OracionBen Michael Oracion 1051 silver badge5 bronze badges1 Answer
Reset to default 0You 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' );