Storing Registered Users’ IP Address in WordPress

As I was working on a project, one of the requirement from my client was to be able to record the IP addresses of the registered users. Luckily, I was using WordPress on that project and easily managed to add such functionality on that site. Today, in this post I will show you how to add such functionality on your self-hosted WordPress site. This is fairly easy to understand and implement. So, lets get started.

The very first thing we need to do is to store users’ IP address on our database and we would do that every time users logs into WordPress.

function grab_users_ip ($login) {
   global $user_id;
   $user = get_userdatabylogin($login);

This code is pretty much self-explanatory. All we are doing here is grabbing the users’ IP address as soon as he or she logs in to system and updating the user meta data(IP address) with a key “user_ip”.

Now, we need to display them on the “Users” admin page for each user. To do that, we need to create a custom column that would display the IP addresses. This can easily be done using the following snippet.

function add_users_ip_column($columns) {
   $columns['user_ip'] = 'IP Address';
   return $columns;}

Now, let’s pull the data(IP Address) that has already been stored on our database. To display the IP addresses of various users, let’s write a function.

function display_users_ip($val,$column,$user_id) {
   $user = get_userdata($user_id);
   switch ($column) { 
      case 'user_ip' : return $user->user_ip; break;
   default: }
   return $return; }

This function would check the users ID number and associated meta key value from the database.

Now, for testing purpose you may log out from the system and then log back. Like any other user it should record your IP address and display them on your “users” admin window. Please remember that, IP address would change every-time you or any other users logs into the system from a different location. However, your functions would record them to the database. Previous IP address of any user would always get overwritten by the latest IP address.

One last thing is, do not forget to place all these codes on your theme’s functions.php page and update the page accordingly. Let me know if you find this snippets to be useful. Enjoy.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.