Additional fields in the Classic WordPress editor

There are several fields you can use to create your posts, such as title, excerpt, content, author and taxonomy terms which come with a standard user interface. But sometimes this is not enough and you want to add more information about your post.

This article shows different implementations to add a user interface to the Classic WordPress editor and how to persist your data.

So let’s add an input field to define the reading time of a post. The classic way to do that is to use a post meta box.

To add a post meta box, we can use the add_meta_boxes action. When this action is triggered, it is the right time to use the add_meta_box function, which requires at least an ID, a title, that will be in the header of the box, and a callable parameter that will be responsible for rendering the meta box content. Every time a post is saved the action post_save is triggered in a POST request which will automatically include your input fields.

Anonymous

Anonymous functions can be a very quick way to implement a post meta box with data persistence.

Functional

With the functional approach, we can add helper functions that can be used to store and access the data in themes or other plugins. Refactoring becomes much easier because the implementation of data persistence is wrapped in custom functions (get_reading_time, set_reading_time) and hidden from the outside. Editors like VSCode provide code completion to use these functions.

Component class

For large projects where you may need more than just one additional meta box, a component-based approach can significantly reduce the lines of code. An IDE like PHPStorm can also help you use the singleton instance properties for easy access to the meta values in themes. Refactoring will be assisted and the implementation of the data persistence is hidden from the outside as well.

My personal favorite is the component-based approach, even though I’m principally a big fan of functional programming. The reason is that the documentation in code comes along with the object property hierarchy. The possibility to use PSR-4 autoloading is a huge help for later code refactoring. But in smaller plugins or in simple themes, the functional approach can also work very well.

In the code examples, I used post meta values to store the reading time. In a real project I would not recommend this. If you want to know why and how to store this kind of data better read the following article: https://medium.com/write-better-wordpress-code/do-not-use-post-meta-fec12a7661

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store