Last Updated on December 22, 2024 by Mike Kipruto
Introduction
Hey there! I wanted to share my experience building a post view counter plugin for my personal site, mike.co.ke. It was a fun project that not only improves user engagement but also provides valuable insights into post performance. Let’s dive into how I structured it and the various hooks and functions I used!
The Class Structure
At the core of the plugin is the wp_post_view_count
class. This encapsulates all functionalities and makes it modular and easy to manage.
class wp_post_view_count {
private $count_key = "mkt_wpb_post_views_count";
private $cache_key = "post_views_cache";
}
- Why use
$count_key
and$cache_key
? Using constants like these helps avoid hard-coding strings throughout the code, making it easier to maintain and refactor later on if needed.
Constructor and Hooks
The constructor sets up various hooks to handle post views tracking. I used the following:
public function __construct() {
add_action("wp", [$this, "track_post_views"]);
}
Moving on, I set up the track_post_views
method to count views:
add_action("wp", [$this, "track_post_views"]);
- What does this hook do? It triggers the view tracking on every page load, but I’ll only count views for single posts and exclude logged-in users to get more accurate statistics.
Tracking Views
Here’s how I handle tracking:
public function track_post_views() {
if (is_single() && !is_user_logged_in()) {
$post_id = get_the_id();
$this->increment_post_views($post_id);
}
}
- Why check for
is_single()
? This ensures views are only counted on individual post pages, avoiding unnecessary counts from archives or index pages.
Inside increment_post_views
, I update the post’s meta value:
private function increment_post_views($post_id) {
$cache = wp_cache_get($this->cache_key . "_" . $post_id);
if ($cache === false) {
$count = (int) get_post_meta($post_id, $this->count_key, true);
$count++;
update_post_meta($post_id, $this->count_key, $count);
wp_cache_set($this->cache_key . "_" . $post_id, $count);
}
}
- Why use caching with
wp_cache_get
? This reduces database queries and speeds up the plugin, as it fetches the count directly from WordPress’s object cache if available.
Admin Features
I found it essential to make the view count visible in the admin area, so I added a column to the posts list:
add_filter("manage_post_posts_columns", [$this, "add_views_column"]);
add_action("manage_post_posts_custom_column", [$this, "populate_views_column"], 10, 2);
- What do these hooks accomplish? They allow me to inject a new column for views in the admin panel and populate it accordingly.
In the populate_views_column
method:
public function populate_views_column($column_name, $post_id) {
if ($column_name === $this->count_key) {
...
echo esc_html($count ? $count : "0");
}
}
- Why use
esc_html
? To ensure that the output is properly sanitized, preventing potential XSS vulnerabilities.
Adding Sorting Capability
To enhance usability, I made the views column sortable:
add_filter("manage_edit-post_sortable_columns", [$this, "make_views_column_sortable"]);
public function sort_views_column($query) {
if (!is_admin()) {
return;
}
$orderby = $query->get("orderby");
if ($orderby === $this->count_key) {
$query->set("meta_key", $this->count_key);
$query->set("orderby", "meta_value_num");
}
}
- Why implement sorting? Allowing the admin to sort by views gives insight into which posts are most popular at a glance.
Dashboard and Admin Bar Display
Lastly, I wanted total views easily accessible, so I added them to the dashboard glance items and the admin bar:
add_action("dashboard_glance_items", [$this, "add_total_views_to_glance"]);
add_action("admin_bar_menu", [$this, "add_total_views_to_admin_bar"], 100);
In the add_total_views_to_glance
, I calculate total views:
$total_views = $this->get_total_post_views();
And I use this same method in the admin bar to display the total views:
public function add_total_views_to_admin_bar($wp_admin_bar) {
if (is_admin()) {
$total_views = $this->get_total_post_views();
$args = [
"id" => "total_post_views",
"title" => "total post views: " . "<b>" . esc_html($total_views) . "</b>",
"meta" => ["class" => "total-views"],
];
$wp_admin_bar->add_node($args);
}
}
- Why display total views in the admin bar? It provides admins with quick access to performance metrics without navigating through multiple screens.
Conclusion
Overall, building this post view count plugin really enhanced my WordPress site. The use of hooks and functions was crucial in streamlining the functionality and integrating it seamlessly into the WordPress ecosystem. If you’re considering creating a similar plugin, I hope this conversation gives you a solid foundation to start from! If you have any questions about specific parts or need further clarification, feel free to reach out here!
Leave a Reply