Estimated Reading Time: 2 min
To track and display post views in WordPress, you can use a custom function. Below is the code for implementing this functionality:
Step 1: Add Code to Functions.php
- Open your WordPress dashboard.
- Go to Appearance → Theme File Editor.
- Select the
functions.php
file of your theme (or child theme). - Add the following code:
// Function to set post views
function set_post_views($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if ($count == '') {
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
} else {
$count++;
update_post_meta($postID, $count_key, $count);
}
}
// Function to get post views
function get_post_views($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if ($count == '') {
return "0 Views";
}
return $count . ' Views';
}
// Hook to increment views when a single post is viewed
function track_post_views($post_id) {
if (!is_single()) return;
if (empty($post_id)) {
global $post;
$post_id = $post->ID;
}
set_post_views($post_id);
}
add_action('wp_head', 'track_post_views');
Step 2: Display Post Views Function
To display the post views on your site, add the following code where you want the views to appear, such as in the single.php template file:
<?php echo get_post_views(get_the_ID()); ?>
Step 3: Avoid Counting Admin Views (Optional)
To prevent admin views from being counted, update the track_post_views
function like this:
function track_post_views($post_id) {
if (!is_single() || current_user_can('manage_options')) return;
if (empty($post_id)) {
global $post;
$post_id = $post->ID;
}
set_post_views($post_id);
}
add_action('wp_head', 'track_post_views');
Step 4: Styling and Placement
You can place the display code in templates like:
single.php
to show views on individual post pages.content.php
orindex.php
to show views in the blog feed.
Use CSS to style the views display if needed.
Would you like help integrating this into your theme or adding additional features like caching?
Discover more from Be-smart
Subscribe to get the latest posts sent to your email.