First, let's try to add post views to the dashboard -> posts. First, we add a new column there:
add_filter('manage_posts_columns', function($columns) {
return array_merge($columns, ['post_views' => 'Views']);
});
Then, we are going to show the number of views. We assume that (Like many other guides on the web), there is a meta key post_views
holding the number of post views.
add_action('manage_posts_custom_column', function($column) {
if ($column === 'post_views') {
$count = get_post_meta(get_the_ID(), 'post_views_count', true);
echo empty($count) ? 'no views :(' : "$count view :)";
}
});
You should be able to see this new column on the posts admin table.
Finally, we have the real code to update the post_views
meta every time a post is visited.
function jj_count_post_views($content)
{
if (is_single() && !is_preview()) {
$postId = get_the_ID();
update_post_meta(
$postId,
'post_views_count',
(int) get_post_meta($postId, 'post_views_count', true) + 1
);
remove_filter('the_content', 'jj_count_post_views');
}
return $content;
}
add_filter('the_content', 'jj_count_post_views');
Please notice that the remove_filter
is necessary, because some plugins use the_content
filter to do more stuff to the content (like SEO plugins), so the_content
will be called multiple times. Thanks to this answer.
Also, remove && !is_preview()
if you want to count all the views, even the preview ones.
P.S. Add all those codes inside theme functions.php and it works.