Code to count post views in WordPress

SEO

By default in WordPress there is no function to count the number of views for posts, if you want to add this function, you must install an external plugin, but installing the plugin is very simple but makes your website you become heavier and reduce the speed of the website to some extent.
Here I will share with you a code with the function to count the number of views for your Website in WordPress.

Code to count the number of views for a post

1. Copy the code below and paste it into the functions.php file of the theme you are using.

//CODE FOR VIEWING
function getPostViews($postID){ $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "<b>01 </b>"; } return $count.' ';
}
// CODE COUNTER VIEW
function setPostViews($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); }
}
//CODE SHOWING THE NUMBER OF VIEWS OF ARTICLES IN DASHBOARDH
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){ $defaults['post_views'] = __('Lượt xem'); return $defaults;
}
function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views'){ echo getPostViews(get_the_ID()); }
}

 

2. CODE CREATE COUNTER FOR ARTICLES

setPostViews(get_the_ID()); //CODE CREATE COUNTER FOR ARTICLES

With the code above you copy it then find the single.php file in the theme directory you are using. Open the file and find the loop that says “while ( have_posts() ) : the_post();” and paste it just below this loop.

3. Finally this code, you can put any position to display the number of views (can be placed in the single.php file to display the number of post views at the bottom of the page, or put in the short description. of the article).

<div class="fas fa-eye">//ICON EYES
<?php echo getPostViews(get_the_ID()); ?>//show views

This is my favorite place where I leave code

Count view
Count view

Good luck!

Leave a Reply

Your email address will not be published. Required fields are marked *