Introduction
Tracking the total page views for WordPress taxonomy terms (like categories, tags, or custom taxonomies) is a common need for website analysis. This guide provides a complete implementation to add this functionality to your site.
Core Implementation
The principle is to create a custom meta field (_views) for each term to store its cumulative view count. This count increments automatically when a user visits the term's archive page.
Step 1: Add Core Functions to Your Theme
Add the following PHP code to the end of your active theme's functions.php file.
/**
* Get view count for a taxonomy term.
* @param int $term_id Term ID. If empty, uses the current queried object's ID.
* @return int View count, defaults to 0.
*/
function fa_get_tax_views($term_id = null) {
if (!$term_id) {
$term = get_queried_object();
if ($term && isset($term->term_id)) {
$term_id = $term->term_id;
}
}
if (!$term_id) {
return 0;
}
$view = (int) get_term_meta($term_id, '_views', true);
return $view;
}
/**
* Increment view count for the currently viewed taxonomy term.
* Hooked to 'get_header'.
*/
function fa_set_tax_views() {
if (!is_tax() && !is_category() && !is_tag()) {
return;
}
$term = get_queried_object();
if (!$term || !isset($term->term_id)) {
return;
}
$term_id = $term->term_id;
$current_views = fa_get_tax_views($term_id);
update_term_meta($term_id, '_views', $current_views + 1);
}
add_action('get_header', 'fa_set_tax_views');
Function Explanation
- fa_get_tax_views: Retrieves the view count from the
termmetatable for a given term ID. - fa_set_tax_views: Increments the view count by 1 for the term of the current archive page.
- add_action: Attaches the increment function to the
get_headerhook, triggering it on page load.
Step 2: Display Views in Templates
After adding the functions, you can display the count in your theme templates.
Basic Usage
In template files like archive.php, category.php, or sidebar.php, insert:
<?php echo fa_get_tax_views(); ?>
Example placement:
<div class='term-views'>Total Views: <?php echo fa_get_tax_views(); ?></div>
Advanced: Get Views for a Specific Term
To display views for a specific term outside its archive page, pass the term ID:
<?php echo fa_get_tax_views(5); // For term ID 5 ?>
Notes & Optimization
- Performance: Direct database updates on each page load may impact high-traffic sites. Consider caching or more efficient tracking methods.
- Scope: The code works for categories and tags by default. Modify the condition in
fa_set_tax_viewsto support custom taxonomies. - Data Initialization: Existing terms will have an empty
_viewsmeta field, treated as 0. Counting starts after activation. - Safety Add code to a child theme's
functions.phpto prevent loss during updates.
Conclusion
This method provides a straightforward way to add view tracking to taxonomy terms in WordPress. It's easily extendable to custom taxonomies and authors, serving as a practical tool for content analysis.