Created
March 12, 2018 15:11
-
-
Save mboynes/f510c3a1098c5a9aa952a3a62abea6c1 to your computer and use it in GitHub Desktop.
Get popular posts using Jetpack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Alley; | |
/** | |
* Popular Posts | |
*/ | |
class Popular_Posts { | |
/** | |
* The number of days to query for post views. | |
* | |
* @var integer | |
*/ | |
public static $jetpack_days = 7; | |
/** | |
* The post types to which to restrict popular posts. | |
* | |
* @var array | |
*/ | |
public static $post_types = [ 'post' ]; | |
/** | |
* Get a number of popular posts from Jetpack. | |
* | |
* The results are cached for an hour. | |
* | |
* @param int $count The number of posts to return. We query 20 posts on | |
* top of this, because the Jetpack stats function can't | |
* restrict by post type. | |
* @return array WP_Post objects. | |
*/ | |
public static function get_from_jetpack( $count ) { | |
$cache_key = 'most-popular-jetpack-' . $count; | |
if ( false === ( $return = get_transient( $cache_key ) ) ) { | |
$return = []; | |
do { | |
if ( ! function_exists( 'stats_get_csv' ) ) { | |
break; | |
} | |
// We add some buffer to the count for post types we don't want. | |
$post_view_posts = stats_get_csv( 'postviews', [ | |
'days' => self::$jetpack_days, | |
'limit' => $count + 20, | |
] ); | |
if ( ! $post_view_posts ) { | |
break; | |
} | |
$post_view_ids = array_filter( array_column( $post_view_posts, 'post_id' ) ); | |
if ( ! $post_view_ids ) { | |
break; | |
} | |
$counter = 0; | |
while ( ! empty( $post_view_ids ) && $counter < $count ) { | |
$post_id = array_shift( $post_view_ids ); | |
$post = get_post( $post_id ); | |
if ( $post && in_array( $post->post_type, self::$post_types ) ) { | |
$return[] = $post; | |
$counter++; | |
} | |
} | |
} while ( 0 ); | |
set_transient( $cache_key, $return, HOUR_IN_SECONDS ); | |
} | |
return $return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment