Writing a custom endpoint for the WP REST API

Introduction

So this was an interesting project. We use a GEL (global experience language) header and footer on nearly all of our core DCC sites. The issue we have come across is being able to maintain these easily.

WP REST API to the rescue! To make this a reality, I created a small plugin that create some custom endpoints for the, what I call, beacon site – the site where the menu will be pulled from by multiple other sites.

So I had a few question which led me to my current solution:

Is there an endpoint I can use already?

Yes. There technically was. Navigation’s, as with most things in WordPress, are a form of post type. Great!

So after figuring out the route I would need, I found a potential stopping point – there was so much data being handed back, but I only need two things:

  1. The link name
  2. the target URL.

The navigation post type object was returning things like IDs, slugs, ID of parent menu items and whole host of others things I didn’t want – all of this was totally unnecessary information to pass over the network.

So this led me on to my next question.

Can I write my own custom endpoint?

Yes! The WP REST API give you the capability to write your own custom endpoints. And, it turns out it is really freaking easy.

There are a few things that you need:

  1. A namespace for your endpoint
  2. an endpoint (with or without a regex that will act as a parseable string)
  3. the method of how this will be called on (post or get)
  4. a callback function.

So here is an example:

// Run an anonymous function in to the REST API init hook
add_action( 'rest_api_init', function () {
    
    // Set up the required information
    $namespace = 'dcc/';
    $endpoint = 'menus/(?P<menu_slug>\w+)';
    $args = array(
        // How the endpoint needs to be called
        'methods' => 'GET',
        // The callback function
        'callback' => 'get_menu_restapi',
    );

    // Add the route 'dcc/menus/<menu_slug>' to the WP REST API
    register_rest_route( $namespace, $endpoint, $args );

}

Pretty simple, right?

Those with a keen eye may have noticed the (?P<menu_slug>\w+). This is going to allow us to use a WP REST API function to get this information from the request being made, and then handle the request as needed.

So is that is? Well, no. At the moment this will fail as the callback function hasn’t been created.

So how do you create a callback function for the WP REST API

Creating your own WP REST API callback function

This is done as any normal function, the trick is to know what information you want to send back.

So, my need for this was to pass back the bare minimal information, via the WP REST API, to the user.

Here is what I wrote:

function get_menu_restapi( WP_REST_Request $request ) {

  // Setup
      // prepare the returnable array
      $menu_items_to_return_as_json = array();
      //... get the slug
      $requested_menu_slug = $request->get_param('menu_slug');
      //... and then get the required menu items from the slug
      $menu_items_from_slug = wp_get_nav_menu_items($requested_menu_slug);


  // Logic
      // If the menu exists and is not empty
      if (!empty($menu_items_from_slug)) :
        //... loop though each menu item
        foreach ($menu_items_from_slug as $menu_item) :
          //... and add the required information to the array that will parse back the JSON
          $menu_items_to_return_as_json[] = array(
            'post_title' => $menu_item->post_title,
            'url' => $menu_item->url,
          );

        endforeach;

      endif;


  // Output
      // Return the required information
      return $menu_items_to_return_as_json;
}

So ‘menu_slug’ was the variable I had as a placeholder in the endpoint I created earlier. I then use the required function to get that variable, and then use that to call on the required navigation items. After that it was a matter of looping each team and assigning the required information to an array.

Once the array was completed, the only thing left to do was return it! The REST API will convert the array in to JSON, so it can be used or decoded at the other end.

Conclusion

Once this was written, I wrapped it up in a WordPress plugin and installed it on the site I needed to pull the menu from – easy.

The WP REST API has a very shallow learning curve. WP have done a fantastic job in making this accessible to developers, and in making it easy to create custom endpoints.

If you haven’t used the WP REST API at all yet, I recommend installing the WP REST API plugin, downloading the desktop application Postman, and having a look at some online tutorials.

You can use the above code to create your own custom endpoint – just pass in a slug to a menu you’ve created and off you go!

Have fun with it and the possibilities are phenomenally fun; I think there might even be a YouTube series on how to theme using the WP REST API

Liam Maclachlan

Working at DCC since late 2015. Developing WordPress themes, and plugins for the front and backend

More Posts - Website

Follow Me:
TwitterLinkedIn

Be the first to Comment

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

 

Comments are held for moderation. House rules