Advertisement
salmancreation

Wordpress count view and popular posts without using plugins

Jan 14th, 2015
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.31 KB | None | 0 0
  1. <?php
  2.  
  3. /* Visit Counter For WordPress by Talkofweb.com */
  4. function getPostViews($postID){
  5. $count_key = 'post_views_count';
  6. $count = get_post_meta($postID, $count_key, true);
  7. if($count==''){
  8. delete_post_meta($postID, $count_key);
  9. add_post_meta($postID, $count_key, '0');
  10. return "0 View";
  11. }
  12. return $count.' Views';
  13. }
  14. function setPostViews($postID) {
  15. $count_key = 'post_views_count';
  16. $count = get_post_meta($postID, $count_key, true);
  17. if($count==''){
  18. $count = 0;
  19. delete_post_meta($postID, $count_key);
  20. add_post_meta($postID, $count_key, '0');
  21. }else{
  22. $count++;
  23. update_post_meta($postID, $count_key, $count);
  24. }
  25. }
  26.  
  27.  
  28. ?>
  29.  
  30. paste this after the_content();. The below code will count for every visit using the setPostViews(); function.
  31.  
  32. <?php setPostViews(get_the_ID());?>
  33.  
  34.  
  35. <?php echo getPostViews(get_the_ID());;?>
  36.  
  37.  
  38. Getting the most popular WordPress post Loop using the Visits Counter:
  39.  
  40.  
  41.   <h3>Popular Stuff:</h3>
  42.     <?php
  43. $popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
  44. while ( $popularpost->have_posts() ) : $popularpost->the_post();?>
  45. <li>
  46. <a href="<?php the_permalink() ?>" title="<?php the_title();?>"><h1><?php the_title();?></h1></a>
  47. </li>
  48. <?php endwhile; ?>
  49. <?php wp_reset_query(); ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement