WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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);
        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);
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        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.


share|improve this question

migrated from stackoverflow.com May 21 '12 at 4:47

This question came from our site for professional and enthusiast programmers.

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 '12 at 7:45

You source? I made a widget that does just that, on this same code.
To sort:

$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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.