How To: Sorting a custom query by views (All time, monthly, weekly, or daily)
-
This is a small revision of @radgh’s post, How To: Sort a custom query by views (All time, monthly, weekly, or daily). There’s a small bug in the code that might lead to unexpected results and so since I can’t edit that topic (at the time of writing only forum moderators can do that) I’m creating a new topic to share the updated code.
—
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./** * Stores views of different time periods as meta keys. * * @author @migueleste / @radgh * @link https://www.ads-software.com/support/topic/how-to-sort-a-custom-query-by-views-all-time-monthly-weekly-or-daily/ * @param int $postid The ID of the current post/page/custom post type. */ 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, 'all', false) ); update_post_meta( $postid, 'views_daily', wpp_get_views($postid, 'daily', false) ); update_post_meta( $postid, 'views_weekly', wpp_get_views($postid, 'weekly', false) ); update_post_meta( $postid, 'views_monthly', wpp_get_views($postid, 'monthly', false) ); } } add_action('wpp_post_update_views', 'custom_wpp_update_postviews');
—
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.
- The topic ‘How To: Sorting a custom query by views (All time, monthly, weekly, or daily)’ is closed to new replies.