Is there any specific reason you are using $wpdb? You can do the same with WP_Query
which is always recommended.
So if your meta key for counting post views is views
then you can run this WP_Query
to return top viewed posts. You can also limit results by posts_per_page
.
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'ignore_sticky_posts' => 1,
'posts_per_page' => '30',
);
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) :
$postnum = 1;
while ( $my_query->have_posts() ) : $my_query->the_post();
echo "Post id " . $post->ID . " has " . get_post_meta( $post->ID, 'views', true ) . " views and rank is " . $postnum . ".<br />";
$postnum++;
endwhile;
endif;
wp_reset_postdata();
?>
EDIT 1
Okey, now I understood what are you asking.
You want to obtain rank of each posts and show it in post list.
To do that first we will need to get all posts sorted by views and store those in an array. After that in each post we will need to find out where each post is located in rank array.
So first we will define global variable in functions.php
file.
$rank_array = array();
Now in your template we will run a custom WP_Query to get rank array. Add this somewhere. Must be outside the loop and must be on the theme php file that shows these posts.
global $rank_array;
$args = array(
'post_type' => 'post',
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'posts_per_page' => -1,
'ignore_sticky_posts' => 1,
'fields' => 'ids',
);
$rank_query = new WP_Query( $args );
$rank_array = $rank_query->posts;
Now we have all the ranked post IDs in our $rank_array
array.
Now in your loop where you are outputing your posts list. You will need to find each posts rank with it’s ID. This must be used inside the loop.
global $rank_array;
$item_rank = array_search( $post->ID, $rank_array ) + 1;
echo "Rank: " . $item_rank . " with " . get_post_meta( $post->ID, 'views', true ) . " views";