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 *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>