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 have defined a post_view_count meta_key to store the number of post views. I would like to get an array of post ids sorted by post_view_count value to use in the functions.php file.

Thanks.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

It's easy. :) You would use get_posts function. See WP_Query class for complete list of parameters that you can use.

function get_posts_by_view_count() {
$ids = array();

$args = array(
    'orderby'   =>  'meta_value_num',
    'order'     =>  'DESC',
    'meta_key'  =>  'post_view_count'
);  
$posts = get_posts( $args );

if( $posts ) {
    foreach( $posts as $post ) {
        $ids[] = $post->ID;
    }
}

return $ids;
}
share|improve this answer
    
is there a way to make this more efficient? Ie return only the IDs as get_posts will actually return everything (wasting resources?). I've looked at get_column but that uses actual SQL which i'd rather avoid. –  daniel Crabbe May 21 '12 at 13:08

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.