Is it possible to get the currently logged in admin’s IP?

Given a wordpress (3.4.x) install that only has 1 admin, how would I grab, from within a plugin, the IP of the currently logged in admin, if there is an admin logged in?

In other words: I need to obtain the IP of the admin, IF there is admin is logged in, and use this IP for other purposes. The request will not necessarily come in from the person logged in as admin. If there is no admin logged in, the function should return empty, as I only need the IP of the admin WHILE he/she is logged in.

Related posts

Leave a Reply

2 comments

  1. This functionality is not directly available, you’ll have to track the logins inside the database(probably as a transient) & check if that transient is available.

    function check_for_admin() {
        $user = wp_get_current_user();
        if(in_array('administrator', $user->roles))
            set_transient('admin_ip', get_ip(), 60*10);
    }
    add_action('init', 'check_for_admin');
    

    After that you can use get_transient('admin_ip') & check if it’s available

    For retrieving the IP, you may use toscho’s code.

    EDIT:

    The 60*10 in the code means if no admin has been active for last 10 minutes, consider them all offline & cleanup the database.

    It’s also possible to delete the transient when user manually logs out, you need to hook into the 'clear_auth_cookie' action to clean up the database.

    function clear_the_transient() {
        $user = wp_get_current_user();
        if(in_array('administrator', $user->roles))
            delete_transient('admin_ip')
    }
    add_action('clear_auth_cookie', 'clear_the_transient');
    

    This code will work in your case when there is only 1 administrator. But this code has a major problem, it deletes the IP from the database even if there are 2 administrators online & only one of them logged out. To overcome that situation, you will have to store the user id as well as their corresponding last activity time in the database.

  2. Like any other IP, they are not different for admins …

    function get_ip() 
    {
        $ip      = '';
        $sources = array (
            'REMOTE_ADDR',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_CLIENT_IP',
        );
    
        foreach ( $sources as $source ) {
            if ( isset ( $_SERVER[ $source ] ) )  {
                $ip = $_SERVER[ $source ];
            } elseif ( getenv( $source ) ) {
                $ip = getenv( $source );
            }
        }
    
        return $ip;
    }
    

    Make sure to validate the value.