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 use this codes in my functions.php to track post views.

/* Functions to track Post Views*/
 function getPostViews($postID){
 $count_key = 'post_views';
 $count = get_post_meta($postID, $count_key, true);
 if($count==''){
    delete_post_meta($postID, $count_key);
    add_post_meta($postID, $count_key, '0');
    return "0 View";
}
return $count.' view';
 }
 function setPostViews($postID) {
 $count_key = 'post_views';
 $count = get_post_meta($postID, $count_key, true);
 if($count==''){
    $count = 0;
    delete_post_meta($postID, $count_key);
    add_post_meta($postID, $count_key, '0');
}else{
    $count++;
    update_post_meta($postID, $count_key, $count);
 }
 }

 /* Track the Views for the post using wp_head hook */
 function trackPostViews ($post_id) {
 if ( !is_single() ) return;
 if ( empty ( $post_id) ) {
    global $post;
    $post_id = $post->ID;
 }
 setPostViews($post_id);
 }
 add_action( 'wp_head', 'trackPostViews');

But i want to display my most viewed post on the sidebar and it is not work. There is dispalyed post but not most viewed. This is my query.

             <?php

 function filter_where2($where = '') {
 $where .= " AND post_date > '" . date('Y-m-d', strtotime('-10 days')) . "'";
 return $where;
 }
 if ( ! $my_paged = absint( get_query_var( 'paged' ) ) )
 $my_paged = 1;

 if ( ! $my_query = get_transient( "7677recent_$my_paged" ) ) 

 {
add_filter('posts_where', 'filter_where2');
$my_query = new WP_Query( "meta_key=post_views&orderby=meta_value&order=DESC&posts_per_page=5&paged=$my_paged" );
set_transient( "7677recent_$my_paged", $my_query, 60 * 60 );
 }
 remove_filter( 'posts_where', 'filter_where2' );
 while ($my_query->have_posts()) : $my_query->the_post(); 
 ?>
share|improve this question
add comment

2 Answers 2

I think the problem is in your transient

set_transient( "7677recent_$my_paged", $my_query, 60 * 60 );

This is currently refreshing every 1 hour you could try changing it to 3 or 5 mins for testins

share|improve this answer
    
I removed the transient - but there is no changes. Returned posts not most viewed. –  Ronin Aug 25 '12 at 9:46
add comment
up vote 0 down vote accepted

I found a problem :)

$my_query = new WP_Query( "meta_key=post_views&orderby=meta_value_num&order=DESC&posts_per_page=5&paged=$my_paged" );

share|improve this answer
add comment

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.