You could create a generic REST API endpoint that just accepted a post ID. I’ve used the default WP_REST_Posts_Controller
to handle some standard checks and format the response:
add_action( 'rest_api_init', function () {
register_rest_route( 'wpse/406874', 'post_data/(?P<id>\d+)', [
'methods' => WP_REST_Server::READABLE,
'permission_callback' => '__return_true',
'callback' => function ( WP_REST_Request $request ) {
$id = (int) $request['id'];
$post = get_post( $id );
$post_type = get_post_type( $post );
$valid_post_types = get_post_types([
'public' => true,
'show_in_rest' => true,
]);
if ( ! in_array( $post_type, $valid_post_types ) ) {
return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), [ 'status' => 404 ] );
}
$controller = new WP_REST_Posts_Controller( $post_type );
$check = $controller->get_item_permissions_check( $request );
if ( $check !== true ) {
return $check;
}
return $controller->get_item( $request );
}
]);
});
This would mean any post of any public post type (& with show_in_rest => true
) would be queryable via:
https://example.com/wp-json/wpse/406874/post_data/<id>