I have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users?
<?php
add_action( 'template_redirect', function() {
if ( is_page( 4848 ) ) {
return;
}
wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );
//wp_redirect( esc_url_raw( home_url( 'index.php?page_id=4848' ) ) );
exit;
} );
I have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users?
<?php
add_action( 'template_redirect', function() {
if ( is_page( 4848 ) ) {
return;
}
wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );
//wp_redirect( esc_url_raw( home_url( 'index.php?page_id=4848' ) ) );
exit;
} );
Share
Improve this question
edited Jan 5, 2022 at 17:16
Pat Gilmour
6122 gold badges5 silver badges16 bronze badges
asked Jan 1, 2022 at 6:47
Blue LiBlue Li
154 bronze badges
2 Answers
Reset to default 1I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted remove_action
on it.
What Maythan8 answered will work but it can be done with fewer functions.
add_action('template_redirect', 'bt_maintenance_redirect');
function bt_maintenance_redirect () {
if (is_page(4848) || current_user_can('administrator')) return;
if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;
}
You used esc_url_raw
but this function is used for escaping url before DB storage, if your url is just for output use esc_url
.
Also better to use wp_safe_redirect
if you are redirecting from and to the same host.
Use user_can( wp_get_current_user(), 'administrator' )
to determine if the user is logged in and is an administrator.
add_action( 'template_redirect', function() {
if ( is_page( 4848 ) ) {
return;
}
if (!user_can( wp_get_current_user(), 'administrator' )) {
wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );
}
exit;
} );