I want to add a widget to my site that shows the most-viewed posts of all time. Every plugin I've tried so far seems to use its own database that initializes upon installation, rather than using internal statistics. Jetpack seems to keep those statistics around but its top-posts widget only provides the last 1-2 days and doesn't have a built-in option for longer time periods.
I've tried hacking the top-posts.php
widget but with limited success. Here's the relevant section from my file:
/**
* Filter the number of days used to calculate Top Posts for the Top Posts widget.
* We do not recommend accessing more than 10 days of results at one.
* When more than 10 days of results are accessed at once, results should be cached via the WordPress transients API.
* Querying for -1 days will give results for an infinite number of days.
*
* @module widgets
*
* @since 3.9.3
*
* @param int 2 Number of days. Default is 2.
* @param array $args The widget arguments.
*/
$days = (int) apply_filters( 'jetpack_top_posts_days', 999999, $args );
/** Handling situations where the number of days makes no sense - allows for unlimited days where $days = -1 */
if ( 0 == $days || false == $days ) {
$days = 2;
}
$post_view_posts = stats_get_from_restapi( array(), 'top-posts?max=11&summarize=1&num=' . absint( $days ) );
If I change the default value of $days
to 10, then the statistics are counted correctly over 10 days. But the number of posts that actually show up is different than what are asked for. With $days
=10, only the top 6 posts show up when you ask for 10 of them. If I set $days
to a huge number like 99999, then it reports there are no posts to show if $count
is 4 or less, and only two posts show up if $count
is 10.
I should add also that, as written, you can't actually set $days=-1
and have it work, because $post_view_posts
uses the absolute value. Of course, it's easy to get rid of that absint
but that doesn't fix this bizarre problem of returning the wrong number of posts...
So...does anyone know the right edits to pull this off?