0

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(); 
 ?>

2 Answers 2

0

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

1
  • I removed the transient - but there is no changes. Returned posts not most viewed.
    – Ronin
    Aug 25, 2012 at 9:46
0

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" );

Your Answer

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

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