I am going to implement a Hot and Trending section on a website. I have seen such sections on many popular websites but can’t really figure out how exactly this works.
Although I assumed Hot section
is most popular posts (based on post views) which I developed by a custom WP_Query
. And it works.
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'meta_key' => 'post_views',
'orderby' => 'meta_value_num',
'ignore_sticky_posts' => 1,
'paged' => $paged,
);
$hot_query = new WP_Query( $args );
But I am stuck on Trending section
. What exactly is the idea behind it for creating a custom query.
I want to know what is the best approach to get content in each section. I tried searching on Google for couple of days but could not really find anything useful.
EDIT
My post views function.
function set_post_views( $postID ) {
if ( is_singular() ) {
$count_key = 'post_views';
$count = get_post_meta( $postID, $count_key, true );
if ( $count=='' ) {
$count = 0;
delete_post_meta( $postID, $count_key );
add_post_meta( $postID, $count_key, '0' );
} else {
$count++;
update_post_meta( $postID, $count_key, $count );
}
}
}
In my personal opinion, this can get a bit resource intensive, so you will need to implement some type of cache system, or even look at transient
What you want to do is to extent your current post view function or even create one on the side for this. You would want to capture each view twice, once for normal page view as you are currently doing ($count_key
) , and secondly for a custom view function using maybe $custom_count_key
Now, this is how $custom_count_key
would work:
-
A page view is recorded when the page (post) is visited as per normal
-
This field is cleaned out (all data deleted) daily/weekly/etc depending on how you would like to define your Trending section
. This again would set the value to 0
at the start of a new day/week/etc
What you will need to do:
-
As stated, either extend or write another page view function to store daily/weekly/etc views
-
Create a function that will run at a specific time daily/weekly/etc (whichever suite your needs better) which will delete/clean-out the values of that meta field.
-
Create your custom query to query an x amount of posts which has the highest amount of views for the specific day/week/etc. The posts been retrieved by this query will differ through out the day/week/etc as each post’s views are increased due to page visits.
-
You can also save the results from a day/week/etc in the db for future reference before deleteting/cleaning out the current values at the end of that specific day/week/etc, but that is up to you and might even be just a waste of time and space
This is just a basic idea that you can use. I’m not in the position to code something like this now, but is would be really nice if you use this idea to post your final working solution to this
Good luck and all the best on this project