Support » Plugin: WordPress Popular Posts » 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://wordpress.org/plugins/wordpress-popular-posts/

Viewing 10 replies - 1 through 10 (of 10 total)
  • If i use all don’t work, because this add plus 1 for all custom_fields

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

    i only can use one of this?

    There shouldn’t be a problem using all four at the same time, if that’s what you mean. They shouldn’t conflict with each other.

    I’m not sure what you mean by:

    “this add plus 1 for all custom_fields”

    sorry about my english, but is that, i wanna use for at the same time, because on my project has three tabs, and each tab show a custom wp query, one is for daily posts, other for weekly and the last for montlhy

    I would actually recommend using the widgets built-in to the plugin for that, unless it’s really not suited to it. Just create three “sidebars” and configure the widget in each one, then display the “sidebar” for each tab.

    You might also try Ultimate Tabbed Widgets to save even more time: https://wordpress.org/support/view/plugin-reviews/ultimate-tabbed-widgets

    If this doesn’t work for you, you should still be able to use the original code. You’ll just need to do three separate queries, so repeat step 2 for each tab, with a different meta key.

    thanks, but this don’t work for me, i going search other solution, thanks again 🙂

    Thanks for this, very helpful.

    One thing I notice was that clearing data from the plugin UI, doesn’t clear anything from post_meta. So you if you want to clear/remove any of the “views_*” I had to delete manually from wp_postmeta.

    Thanks again!

    Is query method make less stress to server than old fashioned way:

    <?php
     
    if ( function_exists('wpp_get_mostpopular') && is_single() ) {
    //если запись тогда:
        global $post;
        $myCats = '';
        $categories = get_the_category( $post->ID );
     
        if ( !empty($categories) ) {
            foreach( $categories as $category ) {
                $myCats .= $category->cat_ID . ', ';
            }
            $myCats = rtrim($myCats, ', ');        // remove trailing comma
        }
     
        $args = array(
           "range" => "all",
            "limit" => 3,
            "thumbnail_width" => 214,
            "thumbnail_height" => 160,
            "stats_views" => 0,
            "excerpt_length" => 155,
            "pid" => $post->ID,
            "cat" => $myCats,
            "post_type" => "post",
            "post_html" => '<li><div class="img">{thumb}</div><div class="title">{title}</div><div class="text">{summary}</div></li> 
     
        );
        wpp_get_mostpopular( $args );
    } else { 
    
    wpp_get_mostpopular( ' post_type="post"&limit=10&stats_views=0&range="weekly"' ) ;}
     
    ?>
    <? }?>
    
    Plugin Author Héctor Cabrera

    (@hcabrera)

    A quick heads-up to anyone using this in the wild: the wpp_get_views() template tag returns a formatted number (eg. 2,034) by default.

    Once your views count are 1000 or higher, the function posted by the OP will store meta data values with formatted numbers (eg. 1,000 instead of 1000) which in turn will make WP_Query fail to sort your posts correctly. The function below fixes this problem:

    /* 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, '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 ) );
    	}
    }

    Have fun!

    Oh this is so good! I need this for last 12 and 6 hours, also 1 hour. Is it possible, Héctor?

    Plugin Author Héctor Cabrera

    (@hcabrera)

    Unfortunately no, that’s not possible at the moment @vicetias.

Viewing 10 replies - 1 through 10 (of 10 total)
  • The topic ‘How To: Sort a custom query by views (All time, monthly, weekly, or daily)’ is closed to new replies.