Put this in your functions.php file
function k99_post_hits( $id, $action ) {
$dl_HitMetaField = '_dl_post_hits'; // hidden Custom field that stores the views
$dl_PostHits = get_post_meta($id, $dl_HitMetaField, true);
switch ($action) {
case 'count' :
if ( $dl_PostHits =='' ) {
$dl_PostHits = mt_rand(10,20);//just for debug-test - remove for real count
delete_post_meta( $id, $dl_HitMetaField);
add_post_meta( $id, $dl_HitMetaField, $dl_PostHits );
}
$dl_PostHits++;
update_post_meta( $id, $dl_HitMetaField, $dl_PostHits );
break;
case 'display' :
echo 'this page was viewed: ' , $dl_PostHits ;
}
}
and this :
function k99_most_popular() {
global $wp_query, $post, $paged, $post_count;
// YOUR QUERY
$query_args = array (
'meta_key' =>'_dl_post_hits',
'orderby' => 'meta_value',
'order' => ASC ,
'posts_per_page' => 5 // how many we want ?
);
// SAVE CURRENT QUERY
$temp = $wp_query;
$wp_query= null;
// CREATE NEW QUERY
$wp_query = new WP_Query();
$wp_query->query($query_args);
$output="<span>";
// THE LOOP, DO WHAT YOU HAVE TO DO HERE
while ($wp_query->have_posts()) : $wp_query->the_post(); {
$output .= '<li><a href="' .get_permalink() .'" title="' . get_the_title(). '"/>'. get_the_title() .'</a></li>';
}
endwhile;
$output .= '</span>';
echo $output;
// SWAP BACK THE PREVIOUS QUERY
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
}
then , in the template file you want to track (typically post &/or single &/or page)
put this in side the loop (preferably as first function before any output):
<?php k99_post_hits( $post->ID, 'count' ); //adding post counter ?>
then – wherever you would like to DISPLAY the count, put this :
<?php k99_post_hits( $post->ID, 'display' ); //adding post counter ?>
to get most “viewed”
<?php k99_most_popular(); //getting post list by views ?>