I did display the most popular posts in my website using a function but the problem is that this function display the most popular posts for all time and I don’t want this.
I want to display (the most popular posts for today)and this list should be updated automatically every day.
Note that I don’t want to use plugins
THis is in functions.php
<?php //fucntion to sort posts bade in thier views.
$args_views = array( 'posts_per_page' => 6, /* get 4 posts, or set -1 for all */
'orderby' => 'meta_value', /* this will look at the meta_key you set below */
'meta_key' => 'post_views_count',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
$myposts = get_posts( $args );
foreach( $myposts as $mypost ) {
/* do things here */
}
?>
and this is my query in index.php
<div class="container">
<?php query_posts($args_views);?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="archive-thumbnail" class="thumbnail">
<div class=" <?php if ( has_catch_that_image() ) { ?>archive-body <?php } ?>">
<div id="archive-img"><img class="media-object-sp" src="<?php echo has_catch_that_image(); ?>" alt="..."></div>
<h4 id="archive-thumbnail-title" style="color:#337ab7;"><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a></h4>
<p id="archive-thumbnail-excerpt"><?php the_excerpt();?></p>
<p class="text-muted"> by: <?php the_author(); ?> | before<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ''; ?></p></div>
</div>
<?php endwhile; ?>
</div>
and this is in Snigle.php
<?php // this is to count the views
setPostViews(get_the_ID()); ?>
You can set a WordPress CRON job to reset the post view counts on daily basis. Please note that: All the view counts will be deleted on daily basis and you can’t get those back.
Sample code for setting up CRON and resetting the view counts:
Paste the above code into your current theme’s
functions.php
file. Try to use Child theme if possible (this is optional though).For more info on setting up CRON jobs through WordPress visit: https://codex.wordpress.org/Function_Reference/wp_schedule_event