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 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.


share|improve this question
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


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.