This post describes how to develop a WordPress plugin that can be used to count visits to a WordPress site. The basic idea is that we will create a table visitor_log in which we will store the timestamp, url_visited, ip_address, and user details of every visit. To do that, we need to:
- Create our plugin file (can name it anything ending with a .php) that will go under our plugin folder. The plugin folder itself is stored under wp-content/plugins. WordPress scans all folders under this directory and displays them in admin plugins dashboard. The plugin file should start with a preamble.
Its also a good idea to declare a namespace to avoid conflicting function names. PHP uses the character in namespace instead of the more common and readable . character used in other languages. So com.foo.myclass becomes comfoomyclass in PHP
- Create the visitor_log table when plugin is activated
- Insert rows into the table when a page is visited
WP provides a register_activation_hook that can be used to do tasks when a plugin gets activated. We can use this hook as follows:
and then in our init_site_counter function, we can create a table like so
Finally for logging visits to the site, we subscribe to the template_redirect event
and add a row as shown below:
visits before the row_id variable overflows and resets to 1. In reality the disk is more likely to become full before the overflow happens. It would be good if we can auto-purge data from the table to prevent a disk-space full error. One elegant way to do this is to reduce the length of the row_id variable to lets say 4 bytes:
Now when the row_id overflows it will start overwriting the oldest records and prevent the table from growing in size which is exactly what we want except that we see an error when trying to insert a row with an id that already exists.
and if we remove the PRIMARY KEY from the table definition
there is an error when trying to create the table. It expects a primary key to be defined