WordPress Popular Posts plugin – Add IP Address to the log – Part 1
![](https://life-adventurer.com/wp-content/uploads/2024/05/banner-1544x500-1.png)
I’m using WordPress Popular Posts – WordPress plugin | WordPress.org to count the number of views and display the Poplular Posts widget. However, it lacks ip address of the users who visit my blog so… let’s do it myself.
Contents
What’s the problem?
WordPress Popular Posts (WPP for short) does not stored user ip address into database so I’m not sure where the view count from. Maybe it’s from my own computer…
Why do I need the ip address?
I want to have a clear understanding of the traffic. Also, just coding for fun.
How do I do it?
In this Part 1, I just keep it simple by modifying the plugin directly. In Part 2, I will make a new plugin to avoid losing my code when updating the original plugin.
Understanding the plugin
Here’s how WPP stores the data in database:
![](https://life-adventurer.com/wp-content/uploads/2024/05/image-1024x753.png)
- wp_popularpostsdata: hold the summary of view count for each post
- wp_popularpostssummary: hold the detail view count for each post every day
- wp_popularpoststransients: hold the cache key
Also, WPP uses API to update the view count. So I need to update that API to save the ip address.
![](https://life-adventurer.com/wp-content/uploads/2024/05/image-1-1024x582.png)
Coding
First, I need to add ip_address to the mysql script so when activating the plugin, it will create the database table with ip_address field.
![](https://life-adventurer.com/wp-content/uploads/2024/05/image-2-1024x623.png)
After that, I update the src/Rest/ViewLoggerEndpoint.php file.
- Function to get IP address from user request
// function to get IP address from user request
public function get_user_ip_from_request() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
- Update function update_views_count
- get ip_address
- Modify the code so it will save the ip_address
![](https://life-adventurer.com/wp-content/uploads/2024/05/image-3-1024x517.png)
![](https://life-adventurer.com/wp-content/uploads/2024/05/image-4.png)
![](https://life-adventurer.com/wp-content/uploads/2024/05/image-5-1024x713.png)
Result
It works!
![](https://life-adventurer.com/wp-content/uploads/2024/05/image-6-1024x785.png)
OK. Part 2 coming soon!!!