Introduction
When developing WordPress themes (such as user profiles), you often need to display the total number of views for an author's posts. This article explains how to get the total post views for the current author (the author associated with the current page or loop).
Core Function
The following function retrieves and outputs the total views for all posts by a specified author. It uses a direct database query for efficiency.
// Get total post views for a specific author in WordPress
if (!function_exists('cx_posts_views')) {
function cx_posts_views($author_id = 1, $display = true) {
global $wpdb;
$sql = $wpdb->prepare(
"SELECT SUM(meta_value+0) FROM {$wpdb->posts}
LEFT JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)
WHERE meta_key = 'views' AND post_author = %d",
$author_id
);
$total_views = intval($wpdb->get_var($sql));
if ($display) {
echo number_format_i18n($total_views);
} else {
return $total_views;
}
}
}
Function Parameters
$author_id(integer): The author's user ID. Default is 1.$display(boolean): Controls function behavior. Iftrue, it echoes the view count. Iffalse, it returns the integer value.
Security and Performance Notes
- Security: The code uses
$wpdb->prepare()to safely parameterize the author ID, preventing SQL injection. - Performance: This method performs an aggregate database query. For sites with a large number of posts, consider caching the result (e.g., using the Transients API) to reduce load.
- Prerequisite: The function assumes post view counts are stored in a custom field named
views. Ensure your theme or plugin uses this meta key.
How to Use
Follow these two steps to display the current author's total post views in your theme.
Step 1: Add the Function to Your Theme
Copy the cx_posts_views function code into your theme's functions.php file.
Step 2: Call the Function in Your Template
In your template file (e.g., author.php, single.php, or within the main loop), insert the following code to display the views:
<?php
if (function_exists('cx_posts_views')) {
cx_posts_views(get_the_author_meta('ID'));
}
?>
To retrieve the value as a variable for further processing, call it like this:
<?php
if (function_exists('cx_posts_views')) {
$author_total_views = cx_posts_views(get_the_author_meta('ID'), false);
echo 'Total Views: ' . number_format_i18n($author_total_views);
}
?>
Summary and Extensions
This method provides a solid foundation for displaying author view counts. For improved performance and flexibility, consider these enhancements:
- Implement Caching: Cache the query result using the Transients API (e.g., for 12 hours) to reduce database load.
- Create a Shortcode: Wrap the functionality in a shortcode like
[author_views]for easy use in posts and pages. - Integrate with User Queries: Modify
WP_User_Queryor store the total in user meta to avoid repeated queries on listing pages.
Using these approaches, you can effectively showcase author engagement metrics throughout your WordPress site.