WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

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 have a custom post type that I want to do a type of news feed for, but I only want to show the ones with the most views. I know I can do a query for an "archive" of my post types, but my question is "how to sort the query by views"?

share|improve this question
What software do you use to count the views? You should not use the WP data base, so there must be some other service with an API for that (like Piwik or Google Analytics). – toscho Apr 9 '12 at 15:29
@toscho I thought that wordpress tracked views already, but it looks like I was mistaken. I'll likely use something like wpsnipp.com/index.php/functions-php/… – Jacksonkr Apr 9 '12 at 15:35
I strongly recommend not to write into your post meta table on each view: Your site will become very slow. You have to break all proxy caches too. Just don't do this. – toscho Apr 9 '12 at 15:39
@toscho What would you recommend for a site with a potential for a lot of traffic? I don't think google analytics will work because I need this data to pull from :( – Jacksonkr Apr 9 '12 at 16:22
I recommend Piwik for statistics, it offers a nice API and there are also plugins on wp.org for it. – toscho Apr 9 '12 at 16:29
up vote 2 down vote accepted

WP post views plugin already does this job very well.

So just install that plugin , then use function like this

<?php if (function_exists('get_most_viewed')): ?>
        <?php get_most_viewed('custom post type name',20); ?>
<?php endif; ?>

For more info, check this FAQ page

share|improve this answer

Hope this code will helpful...

    $right_now = gmdate("Y-m-d");
$qstr = "
    SELECT wposts.* 
    FROM $wpdb->posts wposts, 
    (select postid, sum(pageviews) pageviews 
     from $pageviews_table 
     where day >= '$right_now' - INTERVAL 30 DAY
     group by postid) pv
    WHERE wposts.post_status = 'publish' 
    AND wposts.post_type = 'post'
    AND wposts.ID = pv.postid
    AND wposts.post_date >= '$right_now' - INTERVAL 30 DAY
    ORDER BY pv.pageviews DESC
    LIMIT 10

$max_most_read = 5; // Number of "most read-spots" 
$posts = $wpdb->get_results($qstr);
if ($posts) {
   $i = 0;
    foreach ($posts as $post) {
        if ($i < $max_most_read) {
                $category = get_the_category();
share|improve this answer

Your Answer


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

Not the answer you're looking for? Browse other questions tagged or ask your own question.