When building WordPress applications, one of the most powerful tools that we have at our disposal is the REST API. REST APIs (Representational State Transfer API) provide a structured way to interact with a WordPress site enabling us to retrieve, create, update, and delete data remotely.

What is REST API?

A REST API is a set of conventions for interacting with a server. The WordPress REST API allows the developers to create custom routes that respond to HTTP requests providing a easy way to access the data.

The REST API in WordPress allows us access to various site data such as posts, pages, or custom post types through simple endpoints.

Registering a Basic REST API Endpoint

We can register a route using the register_rest_route function.

function rest_endpoint() {
    register_rest_route('my/v1', '/hello/', array(
        'methods' => 'GET',
        'callback' => 'my_rest_api_callback',
        'permission_callback' => '__return_true',
    ));
}
add_action('rest_api_init', 'rest_endpoint');

function my_rest_api_callback(WP_REST_Request $request) {
    return new WP_REST_Response('Hello!', 200);
}
  • register_rest_route(): Registers a custom route (my/v1/hello/), which will respond to GET requests.
  • my_rest_api_callback(): This callback function is executed when the /hello/ endpoint is hit. It returns a simple greeting message with a 200 HTTP status code.
  • permission_callback: We’ve used __return_true for simplicity, which means the endpoint is open to anyone. In a real-world scenario, you should implement appropriate permission checks to secure your API.

Adding Parameters to an Endpoint

We can use $request->get_param()function to retrieve the a parameter from the request. We can create dynamic responses based on the parameters passed by the user.

function rest_endpoint2() {
    register_rest_route('my/v1', '/hello2/', array(
        'methods' => 'GET',
        'callback' => 'my_rest_api_param_callback',
        'permission_callback' => '__return_true',
    ));
}
add_action('rest_api_init', 'rest_endpoint2');

function my_rest_api_param_callback(WP_REST_Request $request) {
    $name = $request->get_param('name');
    return new WP_REST_Response("Hello, $name!", 200);
}

Creating a Custom Endpoint for Custom Post Types

function my_event_posts_route() {
    register_rest_route( 'my/v1', '/my_event', array(
        'methods' => 'GET',
        'callback' => 'my_event_posts',
        'args' => array(
            'page' => array(
                'validate_callback' => function( $param, $request, $key ) {
                    return is_numeric( $param );
                },
                'default' => 1,
            ),
            'per_page' => array(
                'validate_callback' => function( $param, $request, $key ) {
                    return is_numeric( $param );
                },
                'default' => 10,
            ),
        ),
    ));
}
add_action( 'rest_api_init', 'my_event_posts_route' );

function my_event_posts( $request ) {
    $args = array(
        'post_type' => 'my_event',
        'posts_per_page' => $request->get_param('per_page'),
        'paged' => $request->get_param('page'),
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        $posts = array();
        while ( $query->have_posts() ) {
            $query->the_post();
            $posts[] = array(
                'id' => get_the_ID(),
                'title' => get_the_title(),
                'link' => get_permalink(),
            );
        }
        wp_reset_postdata();

        return new WP_REST_Response( array(
            'posts' => $posts,
            'pagination' => array(
                'total_pages' => $query->max_num_pages,
                'current_page' => $request->get_param('page'),
                'per_page' => $request->get_param('per_page'),
            ),
        ), 200);
    } else {
        return new WP_REST_Response(array(), 404);
    }
}

Conclusion

The WordPress REST API is an invaluable tool for extending WordPress. We can create powerful and flexible endpoints which allows external applications to interact with WordPress data. The REST API provides a structured and standardized way to do so.

Leave a Reply

Your email address will not be published. Required fields are marked *