The Latest

Wordpress API for Beginners

Tuesday, February 23, 2016

How to build API in Wordpress.

1. Brief History
In the beginning, Wordpress was meant as a blogging website and there was little support for API development. Although you can probably modify some rewrite rules to some custom plugin folder to create API in Wordpress, this does requires a lot of work on the developer's side to get it set up. Recently one of the Wordpress plugin called "WP REST API" got integrated into the core library of Wordpress v4.4. This has provided quick and robust way for creating API, which make the developers life much easier. Older version of Wordpress can still install the version 1 of WP REST API to get it working.

2. How to create a simple API
This tutorial will only show you a brief sample of outputting API response. It is assumed you have some knowledge of Wordpress and PHP coding.

The sample code below can be placed in either as part of a theme directory, or a plugin directory. I prefer to place it inside a custom plugin directory as API logic is not related to the look and feel of a theme.

2.1 Plugin Setup
Set up the folder and file structure like below inside the YourProject/wp-content/plugins directory.
/YourPluginName
/index.php

Inside the index.php, populate the following text below to mark it as a plugin. Fill in the details of the plugin as required. Then enable the plugin in the admin dashboard.

/**

 * Plugin Name: <Insert Plugin Name>

 * Plugin URI: <Insert your plugin URL if have one>

 * Description: This plugin is written to handle all FSHD API. Do not deactivate unless discussed with BlackCitrus Developers first. Also minimum  * MySQL version for this plugin to work successfully should be MySQL 5.6.

 * Version: 1.0.0

 * Author: <Your name>

 * Author URI: <Insert a web url>

 * License: GPL2

 */

2.2 Hooking up the plugin

Add the code below to register your API hook.

add_action('rest_api_init', 'register_api_hooks');
function register_api_hooks() {
register_rest_route('api/v1', '/hello-world', array(
'method' => 'GET',
'callback' => 'hello'
));
}

function hello() {
return 'Hello World!';
}

2.3 Testing API
If your website is set up with a web server, then you can see the result at:
http://<your base url>/wp-json/api/v1/hello-world.

The output should be:

"Hello World"

Please note that all api would be prefixed with /wp-json, follow by your namespace. If you do not like the prefix of /wp-json, you can try using a URL rewrite plugin of some sort to change it to something else. If your API needs to return data from the database, you can just fetch the database result using Wordpress SQL functions, and return an array of objects. The API will automatically convert any array or object into a json format. There is no need to perform a php “json_encode()”.

References:

  • http://v2.wp-api.org/
  • https://codex.wordpress.org/Version_4.4
  • https://apppresser.com/using-wordpress-rest-api-mobile-app/