Last active
July 5, 2018 04:36
-
-
Save dasbairagya/24ed1115b15c383a53b0b4978a10531c to your computer and use it in GitHub Desktop.
How to fetch the popular post in wordpress according to views
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* for popular post*/ | |
| /* set the post view count*/ | |
| function wpb_set_post_views($postID) { | |
| $count_key = 'wpb_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); | |
| } | |
| } | |
| //To keep the count accurate, lets get rid of prefetching | |
| remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); | |
| /* get the post view count*/ | |
| function wpb_get_post_views($postID){ | |
| $count_key = 'wpb_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'; | |
| } | |
| ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| if ( have_posts() ) : | |
| while ( have_posts() ) : the_post(); | |
| $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); | |
| wpb_set_post_views($post->ID);//this function has been define in functions.php | |
| echo wpb_get_post_views($post->ID);?>) //this function shows the total no of views for the post. | |
| ?> | |
| //some stufs | |
| <?php endwhile;endif; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment