0

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.

1 Answer 1

3

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;
}
1
  • 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.
    – v3nt
    May 21, 2012 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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