Advertisement
Neolot

WORDPRESS Track post views without a plugin using post meta

Feb 18th, 2012
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.11 KB | None | 0 0
  1. <?php
  2. // Add this to functions.php
  3. function getPostViews($postID){
  4.     $count_key = 'post_views_count';
  5.     $count = get_post_meta($postID, $count_key, true);
  6.     if($count==''){
  7.         delete_post_meta($postID, $count_key);
  8.         add_post_meta($postID, $count_key, '0');
  9.         return "0 View";
  10.     }
  11.     return $count.' Views';
  12. }
  13. function setPostViews($postID) {
  14.     $count_key = 'post_views_count';
  15.     $count = get_post_meta($postID, $count_key, true);
  16.     if($count==''){
  17.         $count = 0;
  18.         delete_post_meta($postID, $count_key);
  19.         add_post_meta($postID, $count_key, '0');
  20.     }else{
  21.         $count++;
  22.         update_post_meta($postID, $count_key, $count);
  23.     }
  24. }
  25.  
  26. // Place this snippet bellow โ€œsetPostViewsโ€ within the single.php inside the loop
  27. <?php setPostViews(get_the_ID()); ?>
  28.  
  29. // Add this to your template
  30. <?php
  31. query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC');
  32. ?>
  33.  
  34. Source:
  35. http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/
  36. http://wpsnipp.com/index.php/loop/most-popular-posts-using-views-post-meta/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement