This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Get #WordPress page view count from Jetpack

The below code snippet will return the page view count by $post_id if you are running the Jetpack WordPress plugin. The count is also stored in a transient that expires every 30 minutes for performance optimization.

/**
 * 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 );
 
}

Full code gist: https://gist.github.com/williamsba/7824876

Props to Greg Rickaby.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.