0

I am owner of a blog/website and I am using this code for tracking post views in site :

  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';
}
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);
    }
}

I want to fetch most viewed posts today, last week, last month to show in sidebar.

Is there any way to sort posts based on post views.

The post views is stored in a custom field post_views

please guide me.

Rias

1
  • There are some plugins for eg. "popular widget" which sort the most viewed posts... but i am not sure if they are able to display results on daily basis...
    – Nasir Zia
    May 21, 2012 at 7:45

1 Answer 1

1

http://www.catswhocode.com/blog/super-useful-wordpress-hacks-and-snippets
You source? I made a widget that does just that, on this same code.
To sort:

<?php
$args = array(
    'post_status' => 'publish',
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'ASC'
);
$the_query = new WP_Query($args); //http://codex.wordpress.org/Class_Reference/WP_Query

//the loop
while ( $the_query->have_posts() ) : $the_query->the_post();
    //do your magic
endwhile;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.