Private Site Statistics REST Endpoint
Adds a /wp-json/site/v1/stats endpoint that returns post, page, comment and user counts to logged-in editors or application-password clients, for reporting tools and status boards.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
register_rest_route( 'site/v1', '/stats', array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
},
'callback' => function () {
$stats = get_transient( 'wpide_rest_site_stats' );
if ( false === $stats ) {
$comments = wp_count_comments();
$users = count_users();
$stats = array(
'posts' => (int) wp_count_posts( 'post' )->publish,
'pages' => (int) wp_count_posts( 'page' )->publish,
'drafts' => (int) wp_count_posts( 'post' )->draft,
'scheduled' => (int) wp_count_posts( 'post' )->future,
'comments' => (int) $comments->approved,
'comments_pending' => (int) $comments->moderated,
'users' => (int) $users['total_users'],
'generated' => gmdate( 'c' ),
);
set_transient( 'wpide_rest_site_stats', $stats, 10 * MINUTE_IN_SECONDS );
}
return rest_ensure_response( $stats );
},
) );
} );
Notes
Access needs the edit_others_posts capability; use an application password to call it from another server.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.