Showing Trending, Hot posts daily, weekly or monthly without plugin

In many times, we need to show trending posts in widgets or in short-codes or in anywhere.But we don’t get any proper way to set views daily, weekly and monthly also throughout all time.The main problem is to get views daily,weekly or monthly.It is easy to get views for all time as because we can set a post meta key for it and add one(+1) each time that post is seen.That’s  very easy.But here today we are going to discuss about the other 3 cases – daily, weekly, monthly.

So here goes the main concept:

1 . Daily – We will add a meta key for each post smd_daily_post_views_count , which will carry number of views for each day.And each post will also have meta key : smd_daily_post_views_count_expiry ,That will contain time in strtotime format, which will be used to check the expiry. i.e: in today that will store time for tomorrow and when today will be tomorrow, at that time, smd_daily_post_views_count will be set to zero( 0 ).

$currenttime    = strtotime('now');
$dailyexpiry    = strtotime(date('Y-m-d', strtotime(' +1 day')));

2. Weekly – Here, we will add a meta key for each post smd_weekly_post_views_count , which will carry number of views for each Week .Also each post will also have meta key: smd_weekly_post_views_count_expiry ,That will contain time in strtotime format, which will be used to check the expiry. i.e: suppose, Our week starts on Saturday. Today that( smd_weekly_post_views_count_expiry ) will store time in strtotime format for next Saturday and when Saturday will come, at that time, smd_weekly_post_views_count will be set to zero( 0 ).Thus on starting of a week we will get zero post views for each posts.

$weeklyexpiry   = strtotime('next Saturday');

3 . Monthly – Same procedure will be applied as before.

$currentDate = new DateTime(date('Y-m-d'));
$currentDate->add(new DateInterval('P1M'));
$firstDayOfNextMonth = $currentDate->format('Y-m-1');

$monthlyexpiry  = strtotime($firstDayOfNextMonth);

 

Setting Up Expiry Meta Key And Adding values to it

Instead of taking wp cron job we are doing it by coding as WordPress Cron job needs further hassle to setup.Now take a look at the code below

add_action( 'init', 'smdSetTrendingExpiry' );
function smdSetTrendingExpiry($post_id){
  $args = array( 
             'posts_per_page'  => -1,
             'post_type'       => 'post',
           );
  $currenttime    = strtotime('now');
  $dailyexpiry    = strtotime(date('Y-m-d', strtotime(' +1 day')));
  $weeklyexpiry   = strtotime('next Saturday');

  $currentDate = new DateTime(date('Y-m-d'));
  $currentDate->add(new DateInterval('P1M'));
  $firstDayOfNextMonth = $currentDate->format('Y-m-1');

  $monthlyexpiry  = strtotime($firstDayOfNextMonth);
  $posts = new WP_Query( $args );
  if($posts->have_posts()){
    while ($posts->have_posts()) {
      $posts->the_post();
      $dailyexpiryvalue = get_post_meta( get_the_ID(), 'smd_daily_post_views_count_expiry', true );
      $weeklyexpiryvalue = get_post_meta( get_the_ID(), 'smd_weekly_post_views_count_expiry', true );
      $monthlyexpiryvalue = get_post_meta( get_the_ID(), 'smd_monthly_post_views_count_expiry', true );
      if($currenttime > $dailyexpiryvalue || $dailyexpiryvalue == ''){
        update_post_meta( get_the_ID(), 'smd_daily_post_views_count_expiry', $dailyexpiry );
      }elseif($currenttime > $weeklyexpiryvalue || $weeklyexpiryvalue == ''){
        update_post_meta( get_the_ID(), 'smd_weekly_post_views_count_expiry', $weeklyexpiry );
      }elseif($currenttime > $monthlyexpiryvalue || $monthlyexpiryvalue == ''){
        update_post_meta( get_the_ID(), 'smd_monthly_post_views_count_expiry', $monthlyexpiry );
      }
    }
  }
  wp_reset_postdata();
}

In upper code, we are Querying all posts then insert meta values for :

smd_daily_post_views_count_expiry, smd_weekly_post_views_count_expiry, smd_monthly_post_views_count_expiry 

 

Insert Views into meta key And clearing after fixed time.

Now it is time to add views for each posts based on daily,weekly,monthly,alltime time span.So we have 4 meta keys one contains total views, another one contains daily views count that is cleared up daily, Another one contains weekly posts views and remaining one contains monthly views.

Now take a look at below function that will initiate on each single post load and store views.

function smd_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
    smd_set_post_views($post_id);
}
add_action( 'wp_head', 'smd_track_post_views');

And main function will be done by smd_set_post_views.

function smd_set_post_views($postID) {
    $total_count_key    = 'smd_post_views_count';
    $daily_count_key    = 'smd_daily_post_views_count';
    $weekly_count_key   = 'smd_weekly_post_views_count';
    $monthly_count_key  = 'smd_monthly_post_views_count';

    $daily_count_expiry    = 'smd_daily_post_views_count_expiry';
    $weekly_count_expiry   = 'smd_weekly_post_views_count_expiry';
    $monthly_count_expiry  = 'smd_monthly_post_views_count_expiry';


    $currenttime    = strtotime('now');
    $dailyexpiry    = strtotime(date('Y-m-d', strtotime(' +1 day')));
    $weeklyexpiry   = strtotime('next Saturday');

    $currentDate = new DateTime(date('Y-m-d'));
    $currentDate->add(new DateInterval('P1M'));
    $firstDayOfNextMonth = $currentDate->format('Y-m-1');

    $monthlyexpiry  = strtotime($firstDayOfNextMonth);

    $count = get_post_meta($postID, $total_count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $total_count_key);
        add_post_meta($postID, $total_count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $total_count_key, $count);
    }

    /*
     ** Daily Counter
     */
    $daily_count = get_post_meta($postID, $daily_count_key, true);
    if($daily_count==''){
        $daily_count = 0;
        delete_post_meta($postID, $daily_count_key);
        add_post_meta($postID, $daily_count_key, '0');
    }else{
        $dailyexpiryvalue = get_post_meta( $postID, $daily_count_expiry, true );
        
        if( $currenttime > $dailyexpiryvalue ){
          update_post_meta($postID, $daily_count_key, '0');
        }else{
          $daily_count++;
          update_post_meta($postID, $daily_count_key, $daily_count);
        }
    } 
    /*
     ** Weekly Counter
     */
    $weekly_count = get_post_meta($postID, $weekly_count_key, true);
    if($weekly_count==''){
        $weekly_count = 0;
        delete_post_meta($postID, $weekly_count_key);
        add_post_meta($postID, $weekly_count_key, '0');
    }else{
        $weeklyexpiryvalue = get_post_meta( $postID, $weekly_count_expiry, true );
        
        if( $currenttime > $weeklyexpiryvalue ){
          update_post_meta($postID, $weekly_count_key, '0');
        }else{
          $weekly_count++;
          update_post_meta($postID, $weekly_count_key, $weekly_count);
        }
    }
    /*
     ** Monthly Counter
     */
    $monthly_count = get_post_meta($postID, $monthly_count_key, true);
    if($monthly_count==''){
        $monthly_count = 0;
        delete_post_meta($postID, $monthly_count_key);
        add_post_meta($postID, $monthly_count_key, '0');
    }else{
        $monthlyexpiryvalue = get_post_meta( $postID, $monthly_count_expiry, true );
        
        if( $currenttime > $monthlyexpiryvalue ){
          update_post_meta($postID, $monthly_count_key, '0');
        }else{
          $monthly_count++;
          update_post_meta($postID, $monthly_count_key, $monthly_count);
        }
    }    
}

Taking the counter increase by one for each time visiting.And if current time (in strtotime format) is greater than daily/weekly/monthly meta views, Then it will reset to zero.Only total count meta key value will remain counting.

Showing Trending posts Daily/Weekly/Monthly:

Now it is time for main part for which we are here.Here I am showing example for weekly posts showing.And you can do the remaining

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
	'post_type' 	=> 'post',
	'posts_per_page'=> -1, //query all posts
	'paged'			=> $paged,
	'meta_key'		=> 'liventis_weekly_post_views_count',
	'orderby'		=> 'meta_value_num',
	'order'			=> 'DESC',
);	

$posts = new WP_Query($args);

That’s it.Now you try yourself to get the daily and monthly also for all time.

Don’t forget to share and comment.I will be glad to be asked questions from you.Good bye

1 Response

  1. 7up says:

    Thank you, buddy you save my day.

Leave a Reply

Your email address will not be published. Required fields are marked *