Generic post sorting using post views
-
Sharing my solution to generic post sorting using post views stored by wpp.
Essentially I’m storing the posts views for the interval I’m interested in a custom field. Then use it to sort posts.
If you know about a more efficient way of doing it, please let me know.
/* Storing 7 days postview count. add to functions.php or plugin*/ function update_postviews($postid) { if (function_exists('wpp_get_views')) { $post_views7 = wpp_get_views( $postid, 'weekly' ); if ( ! update_post_meta ($postid, 'postviews_7days', $post_views7) ) { add_post_meta($postid, 'postviews_7days', $post_views7, true ); } } } add_action('wpp_update_views','update_postviews'); /* end */
/* use custom field to sort post queries */ $args = array( 'cat' => $catid, 'posts_per_page' => 10 , 'meta_key' => 'postviews_7days', 'orderby' => 'meta_value_num', 'order' => 'DESC', ); /* end */
In case you have a high traffic site, updates to the custom field may be much reduced without losing much accuracy. For example updating the count only on around 10% of the post views:
function update_postviews($postid) { if (function_exists('wpp_get_views') && (mt_rand(0,100)<10) ) { $post_views7 = wpp_get_views( $postid, 'weekly' ); if ( ! update_post_meta ($postid, 'postviews_7days', $post_views7) ) { add_post_meta($postid, 'postviews_7days', $post_views7, true ); } } }
Hector, thanks for the great plugin!
cheers,
miguelhttps://www.ads-software.com/plugins/wordpress-popular-posts/
- The topic ‘Generic post sorting using post views’ is closed to new replies.