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
.
There are several ways you could set this up. For example, you could use login_init
action hook. Use the following code, I've added comments for each step:
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;
}
};
Note:
$_SERVER['REMOTE_ADDR']
to get the current ip, but there are other ways too!