Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to get the page view count from Jetpack in WordPress
/**
* Get post pageview count
*/
function wds_post_pageview_count( $post_id ) {
// Check for transient
if ( ! ( $count = get_transient( 'wds_post_pageview_count' . $post_id ) ) ) {
// Verify we're running Jetpack
if ( function_exists( 'stats_get_csv' ) ) {
// Do API call
$response = stats_get_csv( 'postviews', 'post_id='. absint( $post_id ) .'&period=month&limit=1' );
// Set total count
$count = absint( $response[0]['views'] );
// If not, stop and don't set transient
} else {
return 'Jetpack stats not active';
}
// Set transient to expire every 30 minutes
set_transient( 'wds_post_pageview_count' . absint( $post_id ), absint( $count ), 30 * MINUTE_IN_SECONDS );
}
return absint( $count );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment