Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.