admin管理员组

文章数量:1134571

I had done this once before but cannot find my notes for it. I want to be able to redirect readers to another WordPress site, but still be able to access the back end of the current site. Basically it's hiding a site from the public sending them to another site but keeping it up for the admin to access content, yet. I have notes about how to allow admin-only access by way of .htaccess rules using IP addresses, but that would not redirect. I want to be able to redirect everyone but the admin away from the site.

How would that be done?

I had done this once before but cannot find my notes for it. I want to be able to redirect readers to another WordPress site, but still be able to access the back end of the current site. Basically it's hiding a site from the public sending them to another site but keeping it up for the admin to access content, yet. I have notes about how to allow admin-only access by way of .htaccess rules using IP addresses, but that would not redirect. I want to be able to redirect everyone but the admin away from the site.

How would that be done?

Share Improve this question edited Sep 17, 2023 at 17:14 David Borrink asked Sep 17, 2023 at 12:14 David BorrinkDavid Borrink 234 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

You can do it with the "template_redirect" hook. For multisite or simple WordPress. e.g:

add_action('template_redirect', function(){

    $user = wp_get_current_user();
    $userRoles = $user->roles;

    $url = site_url();

    if(!in_array('administrator', $userRoles) && !is_front_page()){
        wp_redirect($url);
        exit;
    }

});

EDIT is_front_page() will work only if "Front page displays" is set. Use is_home() if not.

EDIT #2 Accordind with our discuss below, an example for when you play with multisite and you want redirect according to the current site:

add_action('template_redirect', function(){

    $user = wp_get_current_user();
    $userRoles = $user->roles;

    $url = get_home_url(3);

    if(!in_array('administrator', $userRoles) && get_current_blog_id() != 3){
        wp_redirect($url);
        exit;
    }

});

The ideal method to avoid upsetting search bots that view redirection to other site as deceptive and likely will blacklist, is to set a new home page with the statement that the site has moved and provide a link for user and bots to follow.

That said, if the preference is to automate the action, you'll be better off setting an array of IP addresses that will not be redirected.

functions.php

$allowed_ip = ['12.34.56.7','12.34.56.8'];
function vip() 
{
    if( isset($_SERVER['HTTP_CLIENT_IP']) ) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif( isset($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    
    return $ip;
}

if( !in_array(vip(), $allowed_ip) ) {
  wp_redirect('https://example.com');
  exit;
}

本文标签: