How to create custom WordPress plugin exposing a REST API endpoint
In several previous posts, I discussed adding a Vue application to WordPress in the form of a plugin, as well as creating a plugin with access to the WordPress site’s database. In today’s post, we will create a plugin that allows us to add data to the WordPress database and expose this data as a REST API endpoint. The plugin will enable adding questions and answers for a quiz or test that could be used on an e-learning platform. The mechanism we create can also be used to build any API that exposes data externally.
First, we will prepare the backend of our plugin. Let’s call it web-workshop-quiz-plugin. As we already know, for this purpose we create a subdirectory named web-workshop-quiz-plugin in the WordPress /wp-content/plugins directory, and inside it we place a PHP file with the same name, i.e. web-workshop-quiz-plugin.php.
The header of our main plugin file looks as follows:
<?php
/*
Plugin Name: Web Workshop quiz-plugin
Description: Quiz plugin - just add question and answers, then add shortcode in your page
Version: 1.0
Author: Your Name
*/
We will use the file structure already familiar to us from the previous example, which we will slightly modify:
>api
>includes
>templates
>model
>templates
web-workshop-quiz-plugin.php
As before, in the /includes directory we will place the logic related to database handling, while the /templates directory will contain form templates and lists displaying questions and answers. The remaining directories will be discussed later as the plugin evolves. We start with the database — we add the code already known from previous posts:
<?php
/*
Plugin Name: Web Workshop quiz-plugin
Description: Quiz plugin - just add question and answers, then add shortcode in your page
Version: 1.0
Author: Your Name
*/
register_activation_hook(__FILE__, 'ww_qa_activate');
function ww_qa_activate()
{
//tutaj dodamy kod tworzący naszą bazę danych
}
The register_activation_hook( string $file, callable $callback ) function, which we discussed earlier, is executed when the plugin is activated. The code responsible for creating the database table will be placed in the /includes directory.
Before we move on to writing the code, let’s pause for a moment. This is a good time to think about the data structure of our plugin. In the table, we will need the following columns:
- id – numeric value
- question – string
- answer1 – string
- answer2 – string
- answer3 – string
- answer4 – string
- correct_answer – numeric value
We create a file in which we will set up the database. Let’s call it ww-quiz-data-base-setup.php.
<?php
function ww_quiz_create_table()
{
global $wpdb;
$table_name1 = $wpdb->prefix . 'ww_quizz_questions';
$charset_collate = $wpdb->get_charset_collate();
$sql1 = "CREATE TABLE $table_name1 (
id mediumint(9) NOT NULL AUTO_INCREMENT,
question text NOT NULL,
answer1 text NOT NULL,
answer2 text NOT NULL,
answer3 text NOT NULL,
answer4 text NOT NULL,
correct_answer mediumint(9) NOT NULL,
PRIMARY KEY (id))
ENGINE=InnoDB {$charset_collate};";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql1);
}
Zauważmy, że nazwę każdej funkcji rozpoczynamy prefiksem ww (od nazwy witryny). Robimy to w celu uniknięcia konfliktów z innymi funkcjami w kodzie WordPressa. Ponieważ większość tworzonych przez nas funkcji ma zasięg globalny, prefiksowanie jest dobrą praktyką zalecaną przez WordPressa. Funkcję tworzącą tabelę dodajemy i wywołujemy w pliku web-workshop-quiz-plugin.php. Po aktywacji wtyczki tabela w bazie danych zostanie automatycznie utworzona. Funkcję tworzącą tabelę dodajemy i wywołujemy w pliku web-workshop-quiz-plugin.php.
<?php
/*
Plugin Name: Web Workshop quiz-plugin
Description: Quiz plugin - just add question and answers, then add shortcode in your page
Version: 1.0
Author: Your Name
*/
register_activation_hook(__FILE__, 'ww_qa_activate');
function ww_qa_activate()
{
require_once plugin_dir_path(__FILE__) . 'includes/ww-quiz-data-base-setup.php';
ww_quiz_create_table();
}
At this point, using phpMyAdmin, we can locate the ww_quizz_questions table and manually add quiz questions and answers. Now let’s create an appropriate endpoint in our WordPress installation that will expose the data from the database. In the /api directory, we create a file named ww_quiz_questions_endpoint.php:
<?php
register_rest_route('quizz-api/v1', '/source', array(
'methods' => 'GET',
'callback' => 'ww_handle_get_all1',
));
function ww_handle_get_all1($data)
{
global $wpdb;
$table_name = $wpdb->prefix . "ww_quizz_questions";
$question = $wpdb->get_results("SELECT * FROM $table_name );
return $question;
}
After adding the path /wp-json/quizz-api/v1/source to our website’s address, the quiz data should be displayed in the browser in JSON format.
