Skip to content

Instantly share code, notes, and snippets.

@roykho
Created February 5, 2026 23:07
Show Gist options
  • Select an option

  • Save roykho/391d6504c8abb0fe88e5feb8edd7bd2e to your computer and use it in GitHub Desktop.

Select an option

Save roykho/391d6504c8abb0fe88e5feb8edd7bd2e to your computer and use it in GitHub Desktop.
Alley PHP snippet
<?php
/**
* Registers a REST API endpoint that returns post counts by status,
* cached per capability (editor vs non-editor) to avoid repeated database queries.
*/
add_action( 'rest_api_init', function () {
register_rest_route(
'alley/v1',
'/post-metrics',
[
'methods' => 'GET',
'callback' => 'alley_get_post_metrics',
'permission_callback' => 'alley_can_view_post_metrics',
]
);
} );
// Cache group for post metrics.
const ALLEY_POST_METRICS_CACHE_GROUP = 'alley';
/**
* Permission callback.
*
* Only logged-in users may access post metrics. Non-editors receive only published counts.
*/
function alley_can_view_post_metrics(): bool {
return is_user_logged_in();
}
/**
* Returns post counts grouped by post status.
*
* Cached per capability so editors and non-editors get correct counts without redundant queries.
* - Users with edit_others_posts: publish, draft, private, pending.
* - Others: publish only.
*/
function alley_get_post_metrics( WP_REST_Request $request ): WP_REST_Response {
$can_edit = current_user_can( 'edit_others_posts' );
$cache_key = 'alley_post_metrics_' . ( $can_edit ? 'editor' : 'viewer' );
$cached = wp_cache_get( $cache_key, ALLEY_POST_METRICS_CACHE_GROUP );
if ( false !== $cached ) {
return rest_ensure_response( $cached );
}
// Editors can see everything; others only published content.
$allowed_statuses = $can_edit
? [ 'publish', 'draft', 'private', 'pending' ]
: [ 'publish' ];
$counts = wp_count_posts( 'post', 'readable' );
$response = [];
foreach ( $allowed_statuses as $status ) {
if ( isset( $counts->$status ) ) {
$response[ $status ] = (int) $counts->$status;
}
}
wp_cache_set( $cache_key, $response, ALLEY_POST_METRICS_CACHE_GROUP, MINUTE_IN_SECONDS * 5 );
return rest_ensure_response( $response );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment