Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
    
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
add comment

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

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

1 Answer

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;
share|improve this answer
add comment

Your Answer

 
discard

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