search ]

Register a Custom REST API Endpoint in WordPress

Register a custom REST API endpoint to expose data from your theme or plugin. For more on securing the REST API.

add_action( 'rest_api_init', function () {
    register_rest_route( 'savvy/v1', '/recent-posts/', array(
        'methods'             => 'GET',
        'callback'            => 'savvy_get_recent_posts',
        'permission_callback' => '__return_true',
    ) );
} );

function savvy_get_recent_posts() {
    $posts = get_posts( array(
        'numberposts' => 5,
        'post_status' => 'publish',
    ) );

    $data = array();
    foreach ( $posts as $post ) {
        $data[] = array(
            'id'    => $post->ID,
            'title' => $post->post_title,
            'link'  => get_permalink( $post ),
        );
    }

    return rest_ensure_response( $data );
}

Add to functions.php. Access at /wp-json/savvy/v1/recent-posts/. Set permission_callback to restrict access if needed.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo