
How to create CRUD System with WordPress REST API
Introduction:
In the world of web development, WordPress stands as one of the most versatile platforms, offering not only robust content management capabilities but also a powerful REST API that enables developers to create fully functional applications. In this article, we’ll delve into creating a custom plugin for WordPress that leverages its REST API to implement a complete CRUD (Create, Read, Update, Delete) system for managing employee records.
Setting Up the Plugin:
To begin, let’s create a custom plugin within WordPress. Navigate to your WordPress installation’s plugins directory and create a new folder named custom-plugin
. Inside this folder, create a PHP file named custom-plugin.php
. This file will serve as the entry point for our plugin.
Within custom-plugin.php
, we start by defining the plugin metadata and the activation/deactivation hooks. Additionally, we include the necessary code to create a database table for storing employee records upon plugin activation.
custom-plugin.php
<?php /* Plugin Name: Custom Plugin Description: A custom Plugin for WordPress. Version: 1.0 Author: Your Name */ // Activation hook register_activation_hook(__FILE__, 'custom_plugin_activate'); // Function to create table on plugin activation function custom_plugin_activate() { global $wpdb; $employees_table_name = $wpdb->prefix . 'employees'; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE IF NOT EXISTS $employees_table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, employee_name varchar(100) NOT NULL, department varchar(100) NOT NULL, salary int(10) NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } // Deactivation hook register_deactivation_hook(__FILE__, 'custom_plugin_deactivate'); function custom_plugin_deactivate() { // Deactivation tasks go here }
With this setup, our plugin is ready to create and manage the employees
table within the WordPress database.
Database:
Creating REST API Endpoints:
Next, we’ll define REST API endpoints to handle CRUD operations on our employees
table. We start by registering endpoints for inserting new employee records, fetching all employees, and fetching a single employee by ID.
insert employee record:
// Register API endpoint to insert employee record add_action('rest_api_init', function () { register_rest_route('employee-api/v1', '/insert', array( 'methods' => 'POST', 'callback' => 'insert_employee_record', 'permission_callback' => '__return_true', // No specific permissions required )); }); // Callback function to insert employee record function insert_employee_record($request) { $data = $request->get_json_params(); $name = $data['ename']; $department = $data['department']; $salary = $data['salary']; global $wpdb; $table_name = $wpdb->prefix . 'employees'; $result = $wpdb->insert( $table_name, array( 'employee_name' => $name, 'department' => $department, 'salary' => $salary ), array( '%s', // employee_name '%s', // department '%d' // salary ) ); if ($result) { return new WP_REST_Response(array('message' => 'Employee Record Inserted.', 'status' => true), 200); } else { return new WP_REST_Response(array('message' => 'Employee Record Not Inserted.', 'status' => false), 400); } }
Postman image:
Database:
Fetch all employees:
// Register API endpoint to fetch all employees add_action('rest_api_init', function () { register_rest_route('employee-api/v1', '/get-all', array( 'methods' => 'GET', 'callback' => 'get_all_employees', 'permission_callback' => '__return_true', // No specific permissions required )); }); // Callback function to fetch all employees function get_all_employees($request) { global $wpdb; $table_name = $wpdb->prefix . 'employees'; $results = $wpdb->get_results("SELECT * FROM $table_name", ARRAY_A); if (!empty($results)) { return new WP_REST_Response($results, 200); } else { return new WP_REST_Response(array('message' => 'No Employees Found.', 'status' => false), 404); } }
Single employee by ID:
// Register API endpoint to fetch single employee by ID add_action('rest_api_init', function () { register_rest_route('employee-api/v1', '/get', array( 'methods' => 'GET', 'callback' => 'get_employee_by_id', 'permission_callback' => '__return_true', // No specific permissions required )); }); // Callback function to fetch single employee by ID function get_employee_by_id($request) { $id = $request['id']; global $wpdb; $table_name = $wpdb->prefix . 'employees'; $result = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $id), ARRAY_A); if (!empty($result)) { return new WP_REST_Response($result, 200); } else { return new WP_REST_Response(array('message' => 'Employee Not Found.', 'status' => false), 404); } }
Update an employee by ID:
// Register API endpoint to update an employee by ID add_action('rest_api_init', function () { register_rest_route('employee-api/v1', '/update/', array( 'methods' => 'PUT', 'callback' => 'update_employee_by_id', 'permission_callback' => '__return_true', // No specific permissions required )); }); // Callback function to update an employee by ID function update_employee_by_id($request) { $id = $request['id']; $data = $request->get_json_params(); if (isset($data['employee_name'], $data['department'], $data['salary'])) { $name = $data['employee_name']; $department = $data['department']; $salary = $data['salary']; global $wpdb; $table_name = $wpdb->prefix . 'employees'; $result = $wpdb->update( $table_name, array( 'employee_name' => $name, 'department' => $department, 'salary' => $salary ), array('id' => $id), array( '%s', // employee_name '%s', // department '%d' // salary ), array('%d') // Where clause format ); if ($result !== false) { return new WP_REST_Response(array('message' => 'Employee Record Updated.', 'status' => true), 200); } else { return new WP_REST_Response(array('message' => 'Employee Record Not Updated.', 'status' => false), 400); } } else { return new WP_REST_Response(array('message' => 'Required fields are missing.', 'status' => false), 400); } }
Database:
Delete an employee by ID:
// Register API endpoint to delete an employee by ID add_action('rest_api_init', function () { register_rest_route('employee-api/v1', '/delete/', array( 'methods' => 'DELETE', 'callback' => 'delete_employee_by_id', 'permission_callback' => '__return_true', // No specific permissions required )); }); // Callback function to delete an employee by ID function delete_employee_by_id($request) { $id = $request['id']; global $wpdb; $table_name = $wpdb->prefix . 'employees'; $result = $wpdb->delete( $table_name, array('id' => $id), array('%d') // Where clause format ); if ($result !== false) { return new WP_REST_Response(array('message' => 'Employee Record Deleted.', 'status' => true), 200); } else { return new WP_REST_Response(array('message' => 'Employee Record Not Deleted.', 'status' => false), 400); } }
Database:
These endpoints allow us to perform CRUD operations on our employee records through the WordPress REST API.
Conclusion:
In this article, we’ve explored how to build a complete CRUD system for managing employee records using WordPress and its REST API. By following the steps outlined above, you can extend WordPress beyond its traditional role as a content management system and create powerful custom applications tailored to your specific needs. With the ability to insert, retrieve, update, and delete records via RESTful endpoints, your WordPress site becomes a versatile platform for dynamic web development.