Created
December 6, 2013 14:17
-
-
Save williamsba/7824876 to your computer and use it in GitHub Desktop.
How to get the page view count from Jetpack in WordPress
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
/** | |
* 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