Adding A Stats Column For Jetpack

A feature that I feel is missing from JetPack, is an easy way to view stats for each post.
The data is available there, so we only have to link to it.
Here’s an example for post ID 549:
http://example.tld/wp-admin/admin.php?page=stats&view=post&post=549
We can use the chart bar dashicon to display it:
There are other icons available, like the chart line and chart area icons.
Here’s a plugin to achieve this (PHP 5.4+):
/** * Plugin Name: My Jetpack Stats Column * Plugin URI: https://xlino.com/projects/adding-a-stats-column-for-jetpack/ * Author: Birgir Erlendsson (birgire) * Description: Adds a stats column to the posts table on the edit.php screen * Version: 1.0.1 */ add_action( 'admin_init', function() { // Check if Jetpack Stats module is active if( ! class_exists( 'Jetpack' ) || ! Jetpack::is_module_active( 'stats' ) ) return; // Initialize for the 'post' and 'page' tables if( ! class_exists( 'MyJetPackStatsColumn' ) ) return; $o = new MyJetPackStatsColumn; $o->init( [ 'post', 'page' ] ); } ); class MyJetPackStatsColumn { public function init( array $cpts ) { foreach( (array) $cpts as $cpt ) { $cpt = sanitize_key( $cpt ); add_action( "manage_{$cpt}_posts_custom_column", [ $this, 'column' ], 10, 2 ); add_filter( "manage_{$cpt}_posts_columns", [ $this, 'columns' ] ); } if( is_array( $cpts ) && ! empty( $cpts) ) add_action( 'admin_print_styles-edit.php', [ $this, 'style' ] ); } public function columns( array $columns ) { $columns['my_jetpack_stats'] = ''; return $columns; } public function column( $column, $post_id ) { if( 'my_jetpack_stats' !== $column ) return; printf( '<a href="%s%d" target="_blank" title="%s"><span class="dashicons dashicons-chart-bar"></span></a>', esc_url( admin_url( 'admin.php?page=stats&view=post&post=' ) ), (int) $post_id, esc_attr( __( 'Stats' ) ) ); } public function style() { ?><style> .column-my_jetpack_stats { width: 30px; }</style><?php } } // end classwhere we can adjust the [ ‘post’, ‘page’ ] part to our needs.
One Comment
Thanks, your tutorial helped me to add the state column for Jetpack. Nice job!