Keep Daily Top 10 Posts From Counting Admin Hits
by walter on Dec.23, 2009, under Blogging
Visited 373 times, 1 so far today
Since installing the Daily Top 10 Posts (DTTP) plugin, I’d been trying to figure out a way to keep it from counting my own visits. A few hours of thinking on it, and a few aborted attempts over the last week yielded nothing. Then I learned of a wordpress function that made it pretty easy.
My basic strategy was to use a cookie, but how to keep the cookie applied only to me was the problem. The WordPress tag is_user_logged_in() was the answer, which returns true if the user is logged in. I’m the only registered user, so if anyone is logged in, its me. If I log into wordpress, the is_user_logged_in() sees me and sets a cookie with an expiration of 1 month (arbitrary). Then, the DTTP plugin checks to see if that cookie is set before any operation that would increment the count. If the cookie exists, the count is skipped. I figure I’ll log into the site at least once every month, so there shouldn’t be a situation where the cookie expires. And if I ever clear my cookies for some reason, it will be reset the next time I log in.
To accomplish this, I made a new function in my theme’s function.php to set the cookie.
if (is_user_logged_in()) {
$expire=time()+60*60*24*30;
setcookie("cookiename", "cookievalue", $expire, "/");
}
Then I made a new function in dailytop10.php to check for the cookie.
function exadmin () {
if (isset($_COOKIE["cookiename"]))
return 1;
}
Later in a couple of places a variable $excludepost is defined. Right after each of those, I added
$exadmin = exadmin();
So if the cookie is set, $exadmin = 1
Then in all subsequent sections of the plugin that INSERT data into a table, there was always a check first to verify if $postid existed.
if (!$postid) { ... insert into table}
which says if $postid doesn’t exist, it should do the INSERT command. All I did was look for all those instances before an INSERT and changed it to
if (!$postid && $exadmin !=1) {
which says that if $postid doesn’t exist AND $exadmin isn’t 1, then it should do the insert command.
A similar thing happens prior to UPDATE commands
if (!$viewed) { ... update the table
I looked for all those instances before an UPDATE and changed it to
if (!$viewed && $exadmin !=1) {
There are other locations where a SELECT command is run on a table. I didn’t change anything before those in order to keep the count totals visible. Now as long as I log in at least once a month, the cookie will be set and when I pull up one of my posts, the DTTP totals will display, but my visit won’t be counted. And also, this same cookie can be used by Google Analytics as a filter.
Known problems: It appears that the first visit gets counted regardless of the cookie.