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.

Here is how I am getting the views for one post:

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

Let's say I want to find the most viewed posts from 5,000 posts and I want to show the top 5 most viewed posts.

How can I make a query to achieve this?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

View this section of the Codex to learn how to create a custom query: http://codex.wordpress.org/Class_Reference/WP_Query

Your query will be something like:

$query = new WP_Query( array(
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'posts_per_page' => 5
) );

By default, the ordering will be highest to lowest, thus giving you the "top" 5.

share|improve this answer
2  
How about the function to generate post views count? Where does that come from? –  Brad Dalton Jun 3 at 8:31

View this section of the Codex to learn how to create a custom query: http://codex.wordpress.org/Class_Reference/WP_Query

this code will work

$query = new WP_Query( array(
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'posts_per_page' => 5
) );
share|improve this answer

Your Answer

 
discard

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.