Md Ariful Islam

Md Ariful Islam

Md Ariful Islam

profile-pic
Post views count and display in WordPress without plugins
WordPress

Post views count and display in WordPress without plugins

August 30, 2023

In this article, I will lead you to know about how to count post views and display in WordPress without using plugins.

Step1. Add post views function

Open function.php file

1. Admin dashboard

  • Log in to your WordPress admin dashboard
  • Navigate to Appearance , then Theme Editor.
  • Open the functions.php file.

or

2. Cpanel / FTP

  • Website directory/wp-content/themes/your_theme_name/functions.php

add following code in it. This is a function that initiated for counting post views.

if ( ! function_exists( 'faits_post_view_counter' ) ) :
/** * get the value of view. */
function faits_post_view_counter($postID) {
$count_key = 'faits_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count ==''){
$count = 1;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '1');
} else {
$count++;
update_post_meta($postID, $count_key, $count);
}
}
endif;

Step2. Add post views count

Now similarly add following code in single.php (same path as above mentioned function.php ) but before endwhile loop. This code will count the number of views with the help of above function in a visited post. (Remove from below code)

"<"?php faits_post_view_counter(get_the_ID()); ?">"

Step3. Display count post views

After getting count of post views , it should be displayed where ever you like to display using following code such as in index.php or in single.php itself. You can use Div instead of li as per your requirement in your WordPress website. You can change the icon “fa fa-eye” as you like from fontawesome.

"<"?php if ( get_post_meta( get_the_ID() , 'faits_post_views_count', true) == '') { echo '0' ; } else { echo get_post_meta( get_the_ID() , 'faits_post_views_count', true); }; ?">"

If you are able to implement above codes in your theme, you will definitely count and display your blog post count without using any plugins.