最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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
Add a comment  | 

2 Answers 2

Reset to default 1

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;
} );
发布评论

评论列表(0)

  1. 暂无评论