Getting Started With WordPress API Design

Ogunwole Samuel dare
6 min readJan 19, 2025

--

WordPress APi Design

Hi, you might be wondering how to make an extension to your WordPress Website or thinking of adding customized functionality without using any third-party plugins or themes.

Probably want to leverage existing Woocomerce functionality or a plugin and extend it to use across different platforms such as mobile, Desktop or third-party systems that want to integrate with your WordPress API Site or customize functionality.

Firstly I want you to see WordPress as an engine for your implementation which already has in-built features but is currently exposed to users in the form of themes which was the original scope of WordPress. The good news is that you can expose API from all those functionalities and extend that functionality to suit your system design needs.

See WordPress as a framework to create your custom API Design using PHP as the programming Language

Recently I was working on an e-commerce project which needed me to work with WordPress API to;

Perform onboarding i.e Register, Login, Password activation, and Reset password however, checking the official documentation I could create a user but login is a bit tricky and is for administration purposes so how do I create a system for all users to perform all this operation and Identify them when they make a purchase or add to cart?

This leads me to create my custom API and expose them for web and Mobile consumption and the good thing is WordPress already has methods to create users and check user sessions.

Let's start with creating our first API which will return “Hello World” when we test on Postman.

If you do not know how to set up WordPress you can read the get started from the official Website https://developer.wordpress.org/advanced-administration/before-install/howto-install/

At this point, I believe WordPress is setup already on your local machine or online server.

so let's get started open function.php in the folder of your themes

and insert this Snippet


function helloWorld(){
return 'Hello word';
}
add_action('rest_api_init', function (){
//product search 1
register_rest_route('api/v1', 'hello', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'helloWorld'
));
});

when you test this on your Postman you get something similar to the Image below

Now that seems simple, let's talk about HTTP Verb for API requests such as POST, GET, PATCH/PUT, DELETE

Note the following;

GET is WP_REST_Server::READABLE,
POST is WP_REST_Server::CREATABLE,
DELETE is WP_REST_Server::DELETABLE,
POST, PUT, PATCH is WP_REST_Server::EDITABLE

Now let's create a CRUD operation with WordPress and in the subsequent series we will be creating specific projects to understand more about WordPress API.

There is a deficiency in creating our route and code in function.php of themes as when the theme changes the API stops working which is a very bad design. we will create what we call a plugin in WordPress, it might sound complicated at first but once we grasp the concept it's fairly simple.

Step one go to the plugin folder inside your WordPress project in the directory wp-content/plugins create a folder and call it crudapp or the desired name. Next create a file with an extension of .php example is crudapp.php

and paste the code below in the file

<?php

/*
Plugin Name: CRUD APP
Description: This Plugin create a crud operation
Author: Ogunwole Samuel Oludare
Version: 1.0.0
*/

Note you need to put this comment in your plugin file to enable WordPress to know it is a plugin, afterwards let's create a list of routes for the CRUD operation and paste the code below.

 /**
* Add the endpoints to the API
*/
add_action('rest_api_init', function () {
$namespace = '/api/v1';
$url = 'post';

register_rest_route($namespace, $url, [
'methods' => WP_REST_Server::READABLE,
'callback' => 'getPost'
]);

register_rest_route($namespace, $url.'/(?P<key>[\w-]+)', [
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'createPost'
]);

register_rest_route($namespace, $url.'/(?P<key>[\w-]+)', [
'methods' => WP_REST_Server::EDITABLE,
'callback' => 'updatePost'
]);

register_rest_route($namespace, $url.'/(?P<key>[\w-]+)', [
'methods' => WP_REST_Server::DELETABLE,
'callback' => 'deletePost'
]);

});

Now let's go ahead and create the method (getPost, create post, updatePost and deletePost) specified in the route and test it out on Postman


/**
* @return int[]|string[]|WP_Post[]
*/
function getPost()
{
$args = array(
'numberposts' => 20,
'category' => 4
);
$my_posts = get_posts( $args );

if( ! empty( $my_posts ) ){
return $my_posts;
}
return ['message' => 'No post is avaialble'];
}

/**
* @param [
'post_title' => wp_strip_all_tags( $_POST['post_title'] ),
'post_content' => $_POST['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array( 8,39 )
]
* @return array|string[]|WP_Post|null
*/
function createPost()
{
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $_POST['post_title'] ),
'post_content' => $_POST['post_content'],
'post_status' => 'publish',
'post_author' => 1,
);

// Insert the post into the database
try {
$postId = wp_insert_post( $my_post );
if($postId > 0){
return get_post($postId);
}else{
return ['message' => 'An error occurred'];
}
}catch (Exception $exception){

return ['message' => 'An error occurred'];
}

}

/**
* @param WP_REST_Request $request
* @return string[]
*/
function updatePost(\WP_REST_Request $request )
{
$params = $request->get_url_params();
$postId = $params['key'];
//Note validate this request base on your requirement
$data = array(
'ID' => $postId,
'post_content' => $_POST['post_content'],
);

$update = wp_update_post( $data );
if ($update){
return ['message' => 'Record updated successfully'];
}
return ['message' => 'Fail to updated Record'];

}

/***
* @param WP_REST_Request $request
* @return string[]
*/
function deletePost(\WP_REST_Request $request)
{
$params = $request->get_url_params();
$postId = $params['key'];
$deletePost = wp_delete_post($postId);
if ($deletePost){
return ['message' => 'Record deleted successfully'];
}
return ['message' => 'Fail to delete Record'];
}

The whole content of the plugin will now look like this

<?php

/*
Plugin Name: CRUD APP
Description: This Plugin create a crud operation
Author: Ogunwole Samuel Oludare
Version: 1.0.0

*/
/**
* Add the endpoints to the API
*/
add_action('rest_api_init', function () {
$namespace = '/api/v1';
$url = 'post';

register_rest_route($namespace, $url, [
'methods' => WP_REST_Server::READABLE,
'callback' => 'getPost'
]);

register_rest_route($namespace, $url, [
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'createPost'
]);

register_rest_route($namespace, $url.'/(?P<key>[\w-]+)', [
'methods' => WP_REST_Server::EDITABLE,
'callback' => 'updatePost'
]);

register_rest_route($namespace, $url.'/(?P<key>[\w-]+)', [
'methods' => WP_REST_Server::DELETABLE,
'callback' => 'deletePost'
]);

});


/**
* @return int[]|string[]|WP_Post[]
*/
function getPost()
{
$args = array(
'numberposts' => 20,
'category' => 4
);
$my_posts = get_posts( $args );

if( ! empty( $my_posts ) ){
return $my_posts;
}
return ['message' => 'No post is avaialble'];
}

/**
* @param [
'post_title' => wp_strip_all_tags( $_POST['post_title'] ),
'post_content' => $_POST['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array( 8,39 )
]
* @return array|string[]|WP_Post|null
*/
function createPost()
{
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $_POST['post_title'] ),
'post_content' => $_POST['post_content'],
'post_status' => 'publish',
'post_author' => 1,
);

// Insert the post into the database
try {
$postId = wp_insert_post( $my_post );
if($postId > 0){
return get_post($postId);
}else{
return ['message' => 'An error occurred'];
}
}catch (Exception $exception){

return ['message' => 'An error occurred'];
}

}

/**
* @param WP_REST_Request $request
* @return string[]
*/
function updatePost(\WP_REST_Request $request )
{
$params = $request->get_url_params();
$postId = $params['key'];
//Note validate this request base on your requirement
$data = array(
'ID' => $postId,
'post_content' => $_POST['post_content'],
);

$update = wp_update_post( $data );
if ($update){
return ['message' => 'Record updated successfully'];
}
return ['message' => 'Fail to updated Record'];

}

/***
* @param WP_REST_Request $request
* @return string[]
*/
function deletePost(\WP_REST_Request $request)
{
$params = $request->get_url_params();
$postId = $params['key'];
$deletePost = wp_delete_post($postId);
if ($deletePost){
return ['message' => 'Record deleted successfully'];
}
return ['message' => 'Fail to delete Record'];
}

If you have been able to follow through with this congratulations
let's go ahead and install our plugin and test our API.

If you have any questions let me know and drop a comment for any clarity and watch out for the next series for a complete E-commerce project thanks happy coding.

--

--

Ogunwole Samuel dare
Ogunwole Samuel dare

Written by Ogunwole Samuel dare

Am Software developer who love to write javascript, I am working as Software Architect at Holiday Taxis Group Brighton United Kingdom

Responses (2)