'WordPress: How get most view post posted in last 24 hours
I have this query to get most post views.
I want to retrieve top 3 most viewed topic which are posted in last 24 hours. If the website gets less than 3 topics from last 24 hours it has to retrive the remaining most viewed topics from the previous day.
<?php
$today = getdate();
$args = array(
'meta_key' => 'wpb_post_views_count',
'orderby' => 'meta_value_num',
'posts_per_page' => 3,
'post_type' => 'post',
'post_status' => 'publish',
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday']
)
)
);
$my_query = new WP_Query($args);
while($my_query->have_posts()) : $my_query->the_post();
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
How can do that ?
Solution 1:[1]
Try the code below:
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => '3',
'meta_key' => 'wpb_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post_status' => 'publish',
'date_query' => array(
array(
'after' => '24 hours ago'
)
)
);
$arr_posts = new WP_Query( $args );
if ( $arr_posts->have_posts() ) :
while ( $arr_posts->have_posts() ) :
$arr_posts->the_post(); ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'thumbnail' ); ?>
</a>
<?php wpb_get_post_views(get_the_ID()); ?>
<?php endwhile;
endif;
?>
By writing the above code you can retrieve the most viewed posts from the last 24 hours.
<?php the_post_thumbnail( 'thumbnail' ); ?>
You can change the size of the thumbnail (Featured Image) according to your own requirement. Visit this site for reference: https://developer.wordpress.org/reference/functions/the_post_thumbnail/
Solution 2:[2]
$args = array('orderby'=> 'meta_value_num',"posts_per_page"=> 3, 'date_query'=> array( 'hour'=> 0,));
$my_query = new WP_Query($args);
while($my_query->have_posts()) : $my_query->the_post();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cigien |
| Solution 2 | Stephen Kennedy |
