WordPress Options Class with JSON Support

A while back I had an article title: WordPress Options Class, which was my way of accessing and storing options in WordPress for some of the plugins that I create. After using WordPress for some time now it’s become apparent that storing options in a serialized array in the database is not the best way to do things. I’ve updated my options class to now save the options going forward as JSON. My hope is that other developers will start to do the same.

Why Do It This Way?

At my previous job, there were several times I had to go into some other plugin’s database tables and update a serialized string because some value on our end changed and there was no way to update it through the UI. Using JSON, makes those sorts of changes much easier.

Notes

Using this will allow your options to still be stored as a serialized array, but the next time you save them using this class, the serialized array will be changed to JSON.

The Code

WordPress Options Class

I came up with an object-oriented way of working with my plugin’s options for my work projects.

Creation

So then all I have to do in my class is create an instance of this:
$options = new My_Plugin_Options('my_plugin_options_name');

Accessing

It will store all of your plugin options in 1 record in the database as an array. You can easily access one of the options by doing this:
$this->options->my_first_option

Saving

After updating all the options, we need to save them at once.
$this->options->save();

My Setup

I’ve created a folder inside wp-content/plugins for some code that I use on multiple plugins/themes at work. I don’t have the plugin declaration at the top of the main file, so it doesn’t get recognized as something needing activation. All I do is require the main file in my plugins and themes and that file includes the rest of my classes; the Options class being one of them. I’ve also created a couple classes for dealing with custom post types and taxonomies.