end of week 7

  • Creating custom route in WP_REST
  • CRUD on options from CLI

About everything in WordPress is extensible, even the rest API allows us to create our own endpoints and serve data over them.

It is fairly simple to register a new endpoint, for that we have to use the function register_rest_route()

To this function we have to pass the namespace and the route as parameters

This function internally calls the method register_route() of the class WP_REST_Server

then our route is added to the array of endpoints registered on the server.

Here’s the code to do that

First we need to create a function that will handle request and return something

<?php
function  return_hello( $data ) {
	return "Hello!";
	}
	

Then we have to create another function that will register all the routes, we are currently registering only one here

<?php	
function register_routes(){
	register_rest_route( 'pratik/v1', '/hi', array(
	'methods' => 'GET',
	'callback' => 'return_hello',
	) );
	}

We have registered the route /hi in the namespace pratik/v1

Now we have to hook into the rest init and register this route

	add_action( 'rest_api_init','register_routes');

Done, let’s check it out if it works


CRUD on options from CLI

We can access the options of a site from cli using the wp options command

It has subcommands as below:-

  • delete : Deletes an option.
  • add : Adds a new option value.
  • get : Gets the value for an option
  • list : Lists options and their values..

If this was not enough, we can extend the WP CLI too!

Comments

Leave a Reply

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