Several plugins are there which displays the posts according to number views( number of times the post is viewed). We can achieve the same thing without using a plugin. We can use this code in a particular WordPress theme files. Also it’s very easy to sort the posts according to the post views. Even, we can use the view count to display it side to each post.
Steps:
- Paste the code below into your current theme’s function.php file. Try to use child theme if you are not already having one.(Child theme is optional though)
/** * To display number of posts. * * @param $postID current post/page id * * @return string */ function subh_get_post_view( $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'; } /** * To count number of views and store in database. * * @param $postID currently viewed post/page */ function subh_set_post_view( $postID ) { $count_key = 'post_views_count'; $count = (int) get_post_meta( $postID, $count_key, true ); if ( $count < 1 ) { delete_post_meta( $postID, $count_key ); add_post_meta( $postID, $count_key, '0' ); } else { $count++; update_post_meta( $postID, $count_key, (string) $count ); } } /** * Add a new column in the wp-admin posts list * * @param $defaults * * @return mixed */ function subh_posts_column_views( $defaults ) { $defaults['post_views'] = __( 'Views' ); return $defaults; } /** * Display the number of views for each posts * * @param $column_name * @param $id * * @return void simply echo out the number of views */ function subh_posts_custom_column_views( $column_name, $id ) { if ( $column_name === 'post_views' ) { echo subh_get_post_view( get_the_ID() ); } } add_filter( 'manage_posts_columns', 'subh_posts_column_views' ); add_action( 'manage_posts_custom_column', 'subh_posts_custom_column_views', 5, 2 );
- Open single.php file which is responsible to display each post in WordPress and paste this single line of code inside the loop
<?php subh_set_post_view( get_the_ID() ); ?>
- You can display the post view count by using this line of code inside the WordPress loop on any page.
<?php echo subh_get_post_view(get_the_ID()); ?>
- We can display posts sorted by Post view counts by using the code below.
<?php $args = array( 'numberposts' => 4, /* get 4 posts, or set -1 to display all posts */ 'orderby' => 'meta_value', /* this will look at the meta_key you set below */ 'meta_key' => 'post_views_count', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish' ); $myposts = get_posts( $args ); foreach ( $myposts as $mypost ) { /* do things here */ } ?>
WordPress plugins for post view counts are good but those provide extra functionalities which are not really needed for most of the cases; so why to bloat the setup and add to the response load of the website. Fastness of website matters !! 🙂
Leave a Reply