WordPress Popular Posts plugin – Add IP Address to the log – Part 1

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.

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:

  • 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.

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.

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

Result

It works!

OK. Part 2 coming soon!!!

Leave a Reply 0

Your email address will not be published. Required fields are marked *