How To: Sort a custom query by views (All time, monthly, weekly, or daily)
-
(This is an update of the stickied post “Generic post sorting using post views” by migueleste – which used an outdated action hook and doesn’t work anymore.)
1. Store the view counts for different time frames, for each post, as a meta key.
This code can go in your functions.php file. Mind the comments – they will help keep your website performing well.
/* Storing views of different time periods as meta keys */ add_action( 'wpp_post_update_views', 'custom_wpp_update_postviews' ); function custom_wpp_update_postviews($postid) { // Accuracy: // 10 = 1 in 10 visits will update view count. (Recommended for high traffic sites.) // 30 = 30% of visits. (Medium traffic websites) // 100 = Every visit. Creates many db write operations every request. $accuracy = 50; if ( function_exists('wpp_get_views') && (mt_rand(0,100) < $accuracy) ) { // Remove or comment out lines that you won't be using!! update_post_meta( $postid, 'views_total', wpp_get_views( $postid ) ); update_post_meta( $postid, 'views_daily', wpp_get_views( $postid, 'daily' ) ); update_post_meta( $postid, 'views_weekly', wpp_get_views( $postid, 'weekly' ) ); update_post_meta( $postid, 'views_monthly', wpp_get_views( $postid, 'monthly' ) ); } }
—
2. Create a new WP_Query, sort by view counts within the last week
You can change this to all time, daily, or monthly. Just change the meta key. If you want this to affect the main query, it’s better to modify the default query using the pre_get_posts filter.
// Get the 3 top viewed posts for the week. $args = array( 'post_type' => 'post', 'meta_key' => 'views_weekly', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'posts_per_page' => '3', ); $top_posts = new WP_Query($args);
—
3. Populate the meta keys for immediate use
If you enter the code above, you’ll notice #2 doesn’t work. This is because the meta keys for each post aren’t added until the view count updates. To do this, set $accuracy to 100% and view each post manually. This will populate the meta keys.
You only need to do this step once. When you are done, change the $accuracy again.
https://www.ads-software.com/plugins/wordpress-popular-posts/
- The topic ‘How To: Sort a custom query by views (All time, monthly, weekly, or daily)’ is closed to new replies.