WordPress Customised Data Entry Interface – PT1
December 16, 2017
The client needed a customised backend for a WordPress site to facilitate data entry for a small catalogue of products (fewer than 100 items in total). There were 3 different specific types of product over multiple lines.
Clearly we need to begin by establishing a logical data model. The entity relationships look like this:
[ Product ] is a
Custom Post Type. I also created additional
Custom Taxonomies for fields which would potentially need to be searchable using
WP_Term_Query. This is a rather simplified version of what I successfully implemented – the client version included several additional
[ Product Type ] and
[ Product Line ] are logical entities.
[ Product Version ] is arguably just a grouping of
[ Product ] fields. We don’t actually need to worry about that distinction here – because of the way in which the underlying database structure is abstracted by the WordPress API.
custom meta boxes. The user needs to be able to enter the data for each field. As shown in the example here which is demonstrated with dummy data for an imaginary product. There is a good description of the metabox api at Theme Foundation’s WordPress Meta Boxes: a Comprehensive Developer’s Guide.
Some of those fields are just text boxes – the user can type in anything (though obviously that data needs to be sanitized before being written to the db). Sometimes the user will be selecting an image (or a PDF) from the Media Library (or uploading a new media item). Other times the user may selected from a predefined list (with radio buttons). Or the user may choose an item from a list where the option also exists to add a new item to the list.
When the user has completed or finished editing the fields for a product – then they publish, the same as any other post. But if a user is adding a new field item – for example a new [ Product Line ] then we want them to be able to do that without the need to reload the page in full. We use AJAX to update the database and the page. There is a good tutorial
here at wpmudev.org – about how to implement and secure
wp-ajax. Even with this being on the admin side, rather than user facing, it is important that the callback is properly secured. The following PHP shows how the metabox for [ Product Version ] is implemented:
This is how the AJAX side of that is implemented back in the PHP:
Finally saving [ Product Version ] – called on post: