In this wordPress Plugin tutorial, we’ll show you how to create a simple WordPress plugin which counts post views.
The code is split into two parts, the first will track a view using
counter()
counter()
and
update_post_meta()
update_post_meta()
. The next method will display the number of views in the post using
display_number_of_views()
display_number_of_views()
Here is the full plugin source code.
Plugin Name: An Example Post Views Counter
Plugin URI: https://yourwebsite.com/
Description: A plugin to count the number of views a post receives
Author: Codesnippetsandtutorials.com
Author URI: https://yourwebsite.com/
$views = get_post_meta($post->ID, 'number_of_views', true);
add_post_meta( 'post', $post->ID, 'number_of_views', 0, true);
update_post_meta($post->ID, 'number_of_views', $views);
function display_number_of_views() {
$views = get_post_meta($post->ID, 'number_of_views', true);
echo '<p>' . $views . ' views</p>';
add_action('wp_head', 'counter');
add_action('the_content', 'display_number_of_views');
<?php
/*
Plugin Name: An Example Post Views Counter
Plugin URI: https://yourwebsite.com/
Description: A plugin to count the number of views a post receives
Version: 1.0
Author: Codesnippetsandtutorials.com
Author URI: https://yourwebsite.com/
*/
function counter() {
if (is_single()) {
global $post;
$views = get_post_meta($post->ID, 'number_of_views', true);
if (!$views) {
add_post_meta( 'post', $post->ID, 'number_of_views', 0, true);
$views =0;
}
$views++;
update_post_meta($post->ID, 'number_of_views', $views);
}
}
function display_number_of_views() {
global $post;
$views = get_post_meta($post->ID, 'number_of_views', true);
if (!$views) {
$views = 0;
}
echo '<p>' . $views . ' views</p>';
}
add_action('wp_head', 'counter');
add_action('the_content', 'display_number_of_views');
<?php
/*
Plugin Name: An Example Post Views Counter
Plugin URI: https://yourwebsite.com/
Description: A plugin to count the number of views a post receives
Version: 1.0
Author: Codesnippetsandtutorials.com
Author URI: https://yourwebsite.com/
*/
function counter() {
if (is_single()) {
global $post;
$views = get_post_meta($post->ID, 'number_of_views', true);
if (!$views) {
add_post_meta( 'post', $post->ID, 'number_of_views', 0, true);
$views =0;
}
$views++;
update_post_meta($post->ID, 'number_of_views', $views);
}
}
function display_number_of_views() {
global $post;
$views = get_post_meta($post->ID, 'number_of_views', true);
if (!$views) {
$views = 0;
}
echo '<p>' . $views . ' views</p>';
}
add_action('wp_head', 'counter');
add_action('the_content', 'display_number_of_views');
All done, your posts will now display the number of views each post gets. Make sure you test the code thoroughly before going live with it.