[WordPress] Getting top posts from Jetpack API

Since WordPress’s Jetpack has done a great job for us to collect statistics on our blogs, we should use these stats to benefit our readers. It is way better than using WP-PostViews which will consume our server resources especially the database.

It is quite straight-forward to use Jetpack API, and doesn’t require any complicated authentication system to go through.

We can simply get the top posts by:

if( function_exists( 'stats_get_csv' ) ) {
    $top_posts = stats_get_csv( 'postviews', 'period=month&limit=30' );
}

The returned array is super easy to use:

array(
    [0] => array(
        ['post_id'] => 0
        ['post_title'] => 'Home page'
        ['post_permalink'] => 'http://www.example.com/'
        ['views'] => 6806
    )
    [1] => array(
        ['post_id'] => 8005
        ['post_title'] => 'Hello World!'
        ['post_permalink'] => 
        ['views'] => 1845
    )           
    /* till item [29] */

Example code from brasofilo

Note that it is advised to cache to result for at least 180 seconds (as mentioned in Jetpack API’s response)

Reference: get view vount from Jetpack


Also published on Medium.

Leave a Reply

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