WordPress: Show number of page views without plugin
Do you want to show the number of times a page or post has been viewed in WordPress? Displaying the number of page views can be very effective proof of a website or blog post’s popularity. There are several WordPress plugins that allow you to show page view counts. One such plugin is WP-PageView. It is very effective and has lots of features. What if you don’t need all those features and just want to show the page view count? Here is a very simple and effective code for logging the number of page views and showing them in WordPress.
Paste the following code in the functions.php file of your theme.
<?php // function to count views. 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); } } // function to display number of posts. 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 "0 View"; } return $count.' Views'; } // Add it to a column in WP-Admin 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'] = __('Views'); return $defaults; } function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views'){ echo getPostViews(get_the_ID()); } } ?>
With the above code, the system is in place to start counting pageviews and show the stats in your WordPress website. However, we need to implement it in pages.
Add the following inside the WordPress query loop in single.php, which is used to show posts in WordPress. This will start logging in the pageviews.
<?php setPostViews(get_the_ID()); ?>
Now, insert the following code also inside the WordPress query loop in single.php where you want to show the number of pageviews.
<?php getPostViews(get_the_ID()); ?>
As the above code creates and saves a “post meta” for each WordPress post, it can be used to sort posts as well. You can use the following WordPress post query to order posts in order of page views.
<? query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC'); ?>
Source: WPSnipp