How to get most visited posts of the week?

2019-07-18 17:23发布

Whenever a user visits a post, I have a simple function that triggers that simply adds +1 to a single custom field visit counter field for that post.

This means I can easily get the most visited posts of all time using a new WP_Query() using the meta value to sort, but I can't for the life of me figure out a good way to only get the most visited posts from the last X days.

As I'm simply increasing the custom field of each post by 1, I understand that there is no reference to dates or anything, but I can't imagine a good coding solution to make that happen.

Is there a WordPress way to determine how many times a custom field changed over the last 7 days?

标签: php wordpress
2条回答
▲ chillily
2楼-- · 2019-07-18 17:47

A solution would be to have a counter per-day.

Say you have a counter for today - let's call it 09052016, and another one for tomorrow called 10052016. Then to get the views over the last 7 days, you just take the last 7 days' counters and add them together.

An easier solution would possibly be to name these incrementally, so you have 000001, 000002, 000003 and so forth.

This would make it a lot easier to write a PHP function that would allow you to take say 000182 and the previous 6 counters.

Ranking top posts over the last 7 days would also be possible by calculating the value of the values:

x + (x-1) + (x-2) + (x-3) + (x-4) + (x-5) + (x-6)

I am not sure whether or not this is the most efficient solution.

You could also have a counter per day and a counter per week, that after 1 day subtracts the amount of views from the day 6 days back.

查看更多
叼着烟拽天下
3楼-- · 2019-07-18 18:11

Try This way..

<?php
query_posts( array( 'meta_key' => 'views', 'orderby' => 'meta_value_num', 'order' => 'DESC','showposts' => '6', 'w' => '. date( "W", current_time( "timestamp" ) )' ) );
while(have_posts()) : the_post();?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;wp_reset_query();
?>
查看更多
登录 后发表回答