Custom WordPress REST API
Written on October 30, 2019
Currently, I am using wpdb plugin boilerplate. For this quick experiment, I create a plugin name with code
- Open /includes/class-code.php. Add function mrinal_information() with rest_api_init action hook. mrinal_information() will develop at /admin/class-code-admin.php
$this->loader->add_action( 'rest_api_init', $plugin_admin, 'mrinal_information' );
2. Open /admin/class-code-admin.php. Develop mrinal_information() in Code_Admin class.
In mrinal_information(), register endpoint with register_rest_route() with
a. Endpoint namespace
b. Route’s name
c. Array of methods and callback. As callback, we will declare information_function().
Finally, mrinal_information() will be,
public function mrinal_information() { register_rest_route( 'mrinal/v1', 'information', array( 'methods' => 'GET', 'callback' => array( $this, 'information_function' ), ) ); }
3. For the experiment, in information_function(), I declare the name and URL of my photo. Information stored as Object. In this object, I will insert data. Finally, I returned this object at this defined endpoint.
Lastly, information_function() will be,
public function information_function() { $info = new stdClass(); $info->name = "Mrinal"; $info->cover = "http://localhost/rest/wp-content/uploads/2019/10/africa-1854308_1920.jpg"; return $info; }
I can test this JSON is published at http://localhost/rest/wp-json/mrinal/v1/information. Screenshot of result is