How to Create Custom Endpoints in WordPress REST API (with live example)

Sometimes you need to customize WordPress REST API to return fewer columns or to have a custom structure. Fortunately, it’s easy to create Custom Endpoints to WordPress REST API.

Use register_rest_route to define your own namespace and version. Then in your callback function, use Custom Queries to define the required results.

Put the code in your functions.php.

Example

The following code, although simplified, could be the basis for creating Ajax Search on your WordPress website.

function register_demo_search()
{
    register_rest_route('pontikis/v1', 'demoSearch', [
        'methods'  => WP_REST_SERVER::READABLE,
        'callback' => 'demo_search_results'
    ]);
}

function demo_search_results($data)
{
    $search_query = new WP_Query([
        'post_type'      => ['post', 'page'],
        'posts_per_page' => -1,
        's'              => sanitize_text_field($data['term'])
    ]);

    $results = [];

    // basic error handling
    if (false === isset($data['term']) ) {
        return [
            'error' => 'No term defined...'
        ];
    } else {
        if (true === empty($data['term'])) {
            return [
                'error' => 'Please give a term to search...'
            ];
        } else {
            if (4 > mb_strlen(trim($data['term']))) {
                return [
                    'error' => 'The search term must contain at least 4 characters...'
                ];
            }
        }
    }

    // proceed to database query
    while ($search_query->have_posts()) {
        $search_query->the_post();

        array_push($results, [
            'title'     => get_the_title(),
            'permalink' => get_the_permalink(),
        ]);
    }

    wp_reset_postdata();

    return $results;
}

add_action('rest_api_init', 'register_demo_search');

Try the following URL, or experiment with “term" parameter:

https://www.pontikis.net/wp-json/pontikis/v1/demoSearch?term=docker

This will return the titles of all the articles (posts and pages) containing the term “docker”.

Response (at the time of writing the article):

[
   {
      "title":"Docker In A Nutshell",
      "permalink":"https://www.pontikis.net/blog/docker-in-a-nutshell"
   },
   {
      "title":"mkcert – Create and Trust SSL for Development",
      "permalink":"https://www.pontikis.net/blog/ssl-for-development-with-mkcert"
   },
   {
      "title":"AWS vs Azure: Which Cloud Platform Should You Learn First?",
      "permalink":"https://www.pontikis.net/blog/aws-vs-azure-which-should-you-learn-first"
   },
   {
      "title":"How To Setup The Perfect Linux Workstation With Xubuntu 20.04 LTS Focal Fossa",
      "permalink":"https://www.pontikis.net/blog/setup-linux-workstation-with-xubuntu-20-04"
   }
]

Reference

See also