How To Make Custom WordPress Rest API Endpoints

More and more web services are nowadays consuming information and processing data directly from blogs. A JSON WordPress Rest API endpoint and text scraping are two common methods of linking blogs and web services. In this article, I am going to describe how I have created a JSON endpoint for the Cooked WordPress plugin to query recipes that will be used by a mobile app.

There is no doubt that the Cooked WordPress Plugin is one of the best alternatives for a food blog. It has amazing easy-to-use features that help you manage and add new recipes to your food blog efficiently like our sister blog WellbeingBarista food and lifestyle blog. Additionally, we thought that we could use the same recipes for a Recipes/Food app but felt that exporting and importing the data manually would be a little messy and inefficient.

So why not adding a JSON endpoint for the Cooked plugin?

Retrieving Recipes Stored by the Cooked WordPress Plugin

It seems that as administrators of the blog, we might be a little bit picky and managed to find out a missing feature! Currently, at the time of writing, there is no JSON endpoint API that allows you to dynamically export recipes albeit this is a very important feature if you need to hook up any web services with the blog.

Nevertheless, after investigating how the recipes are stored in the main WordPress database, it was trivial to come up with a spartan functional way to create this JSON endpoint. This simple solution offers a Rest API with two JSON endpoints:

  1. An endpoint to get a list of available recipes – https://your_domain.com/wp-content/plugins/your_plugin_name/api_name.php
  2. Another endpoint to return the detailed recipe object – https://your_domain.com/wp-content/plugins/your_plugin_name/api_name.php?recipeId=261 where 261 is an id retrieved from the response of the first endpoint.

Unfortunately, there was no database field to indicate the last modification date of the recipe, hence an SHA-based hash function was used to generate the version. A version is a very important piece of information for any web service consuming the JSON endpoint API. Otherwise, it would not be efficient to react to distinct recipe changes or updates.

WordPress Rest API – the PHP Source Code

Now let’s look at the PHP code that creates the JSON WordPress Rest API with two endpoints.. It should be noted that in order not to replicate config items, it makes use of the existing WordPress configuration.

<?php require "../../../wp-config.php"; ?> 
<?php 

$servername = DB_HOST; 
$username = DB_USER; 
$password = DB_PASSWORD; 
$dbname = DB_NAME; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
     die("Connection failed: " . $conn->connect_error); 
} 
if (!isset($_GET['recipeId'])) { 
     // No recipe id is set, hence return all the available ones. 
     $sql = "SELECT postId as recipeId, SHA(metaValue) as version from (select post_id as postId, meta_value as metaValue from wordpress.wp_postmeta where meta_key = '_recipe_settings') AS innerTable"; 
     $result = $conn->query($sql); $resultArray = array(); 
if ($result->num_rows > 0) { 
     // output data of each row 
     while ($row = $result->fetch_assoc()) {  
          $resultArray[] = $row; 
     } 
     echo json_encode($resultArray); } else { 
     echo "{}"; 
     } 
} else { 
     //Load the meta for specified recipe, avoiding SQL injection 
     $stmt = $conn->prepare("SELECT meta_value FROM wordpress.wp_postmeta WHERE meta_key = '_recipe_settings' and post_id = ?"); 
     $stmt->bind_param('i', $_GET['recipeId']); 
     $stmt->execute(); $result = $stmt->get_result(); 
     if ($result->num_rows > 0) { 
           $row = $result->fetch_assoc(); 
           echo json_encode(unserialize($row["meta_value"])); 
     } else { 
           echo "{}"; 
     } 
} 
$conn->close(); 
?>
Code language: PHP (php)

The PHP file ‘api_name.php’ was copied into a directory under plugins. However, it can be created anywhere as long as the reference to wp-config.php (line 1) is updated accordingly.

Testing the API

Now, using an API Testing Tool such as Postman or SoapUI call the two endpoints with the required parameters and check the responses.

The result should be like the following sample responses.

Sample Responses

A Sample Response of the WordPress Rest API Endpoint that returns a recipe detail given an Id.
Sample endpoint’s response when requesting for recipe details

A Sample Response of the WordPress Rest API Endpoint that returns all recipe Ids
Sample endpoint’s response when requesting all recipes in database.

Conclusion

After setting up the PHP file, your Cooked WordPress Plugin installation will have a WordPress Rest API. Beware that this is only a proof of concept that happened to extract data saved by the Cooked Plugin but the concept can be used for any data found on WordPress.

Scroll to Top