I have a snippet to redirect all users to a maintenance page. How do I exclude users with admin role?

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;
} );

Topic php maintenance Wordpress

Category Web


I 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;
} );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.