简体   繁体   中英

Wordpress - Redirect based on IP address

I'm making a Wordpress function that redirects the user to a different page when they're on a certain IP address. The code however does not function properly and I can't get it to work.

function ip_based_login() 
{
    if ($_SERVER['REMOTE_ADDR'] == '95.81.51.134') 
    {
        wp_redirect("examplewebsite.com/login2"(site_url($wp->request)));
    } 
    else 
    {
        exit;
    }
}

you dont really need to write a code for that The best thing about wordpress is that there are tons of stuff already available You can use the following plugin for your requirements https://wordpress.org/plugins/shortcode-redirect/

site_url expects a path to attach to the site url(eg: site_url('hello') => https://example.com/hello .

$wp->request contains the path of the request which means doing site_url($wp->request) will return you the url you are on.

here is a working snippet, just replace $url with the url you want to redirect to.

function ip_based_login() {
    $visitor = $_SERVER['REMOTE_ADDR'];
    $redirectTo = site_url('login2');

    if (preg_match("/95.81.51.134/",$visitor)) {
        wp_redirect($redirectTo);
    }

    exit;
}

keep in mind that placing this snippet in functions.php without hooking it to a specific action can cause an infinite redirect loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM