Example Custom REST API Endpoint
Registers a read-only endpoint at /wp-json/wpide/v1/latest that returns your latest posts in a compact format, as a starting point for your own API routes.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
register_rest_route( 'wpide/v1', '/latest', array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => '__return_true', // Public, read-only data.
'args' => array(
'count' => array(
'default' => 5,
'sanitize_callback' => 'absint',
'validate_callback' => function ( $value ) {
return is_numeric( $value ) && $value >= 1 && $value <= 20;
},
),
),
'callback' => function ( WP_REST_Request $request ) {
$posts = get_posts( array(
'numberposts' => (int) $request->get_param( 'count' ),
'post_status' => 'publish',
) );
return rest_ensure_response( array_map( function ( $post ) {
return array(
'id' => $post->ID,
'title' => get_the_title( $post ),
'url' => get_permalink( $post ),
'date' => get_post_time( 'c', true, $post ),
'excerpt' => wp_strip_all_tags( get_the_excerpt( $post ) ),
'image' => get_the_post_thumbnail_url( $post, 'medium' ) ? get_the_post_thumbnail_url( $post, 'medium' ) : null,
);
}, $posts ) );
},
) );
} );
Notes
Change the namespace, route and callback to build your own endpoint. Make permission_callback stricter for anything that is not public.
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.