0

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"?

5
  • 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).
    – fuxia
    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
  • 3
    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.
    – fuxia
    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
  • 1
    I recommend Piwik for statistics, it offers a nice API and there are also plugins on wp.org for it.
    – fuxia
    Apr 9 '12 at 16:29
2

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')): ?>
    <ul>
        <?php get_most_viewed('custom post type name',20); ?>
    </ul>
<?php endif; ?>

For more info, check this FAQ page

1

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) {
        setup_postdata($post);
        if ($i < $max_most_read) {
                $category = get_the_category();
                $i++;
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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