Adding CRUD to your WordPress site

CRUD?

CRUD is short for Create-Read-Update-Delete, and that is computer-lingo for everything you need to keep one or more database tables updated.

MYSQL

Since WordPress by default needs MySQL, one of the most popular softwares for small-to-medium databases, it is easy to add code to a WordPress site that accesses tables in that database. You can also create new tables, as well as accessing completely external databases.

You could use a generic plugin like wpDataTables, but the downside is that it exposes the whole database. You could also include phpMyAdmin which is the tool of choice when working with MySQL via the web. This is cool for admins, but what if you want end-users to maybe edit records in just one  table(or a couple of tables) ?

REFRESH OR REST

Basically you will have to take one of two routes. Both include quite a lot of coding I’m afraid.

REFRESH

The first I call REFRESH because it involves generating everything on the backend. So you have to have different pages for each action (causing refresh) which is frowned upon today. But there are valid use cases, since the upside is short development time.

You have the following modules (although your naming scheme may be different of course) :

  • index.php – lists all items, with edit and delete buttons
  • new.php – presents an empty form
  • edit.php – callable from index.php only. Presents status, index or the same record still in edit mode, (your choice).
  • update.php – called from new (insert) or edit (update). Detected in server dep on whether “id” is passed in parameters.
  • delete.php – called from index or edit. Must have “id” as parameter. Presents status or index.

You can acess the WordPress database using regular PHP MySQL utilities, or by using the WordPress library. The first is described here here: http://www.php.net/manual/en/book.mysqli.php and the latter here https://www.smashingmagazine.com/2011/09/interacting-with-the-wordpress-database/

I would strongly recommmend to use the WP utility!

REST

The second route is using REST. You create a backend in your language/framework of your choice while writing the UI using a suitable JS framework. By letting WordPress serve the JS you integrate it in your site.

Which way is the best? Well option A is easier I think, while option B is more modern and gives you a SPA-like experience. The UI could be written in React or Vue, while the backend could be ASP.NET MVC or Ruby on Rails.

Sound interesting? Read this article for more details: How to create a CRUD system in WordPress – 2018

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.