-1

I want to make a plugin for my own WordPress website, in which if the login page of WordPress is accessed from a specific address, then it is shown, otherwise it is redirected to homepage.

Example:

if(current_page == login && ip_address != xxx.xxx.xxx.xxx)
 redirect_to_homepage;

I have made a simple plugin that reads ip address of current visitor and can access current page url, but the plugin does not run on the login page. The plugin executes on all public pages like example.com/index.php, but not on example.com/wp-login.php

I assume that I should use:

add_action('template_redirect', 'ss_check_login');

so that I can redirect page before headers are sent. Am I correct?

How to execute a plugin (and its code) on WordPress login page.

And I want to know what add_action to use for redirection?

I do not want to use .htaacess.

4

1 回答 1

3

您可以通过多种方式进行设置。例如,您可以使用login_init动作挂钩。使用以下代码,我为每个步骤添加了注释:

add_action('login_init', 'redirecting_users');

function redirecting_users()
{
    // Getting the current page
    global $pagenow;

    // Whitelisting ip addresses in an array so that you could add more than one ip address
    $allowed_ip_addresses = array('0000000000', '111111111111');

    // Getting the current ip of the user
    $current_ip_address = $_SERVER['REMOTE_ADDR'];

    if (
        'wp-login.php' == $pagenow
        &&
        !in_array($current_ip_address, $allowed_ip_addresses)
       ) 
    {
        wp_safe_redirect(site_url());
        exit;
    }
};

笔记:

  • 就像我在代码注释中所说的那样,我使用了一个数组来将 IP 地址列入白名单,这样您就可以添加多个 IP 地址。
  • 我以前$_SERVER['REMOTE_ADDR']是获取当前ip的,不过还有其他方法!
于 2022-01-01T15:28:35.560 回答