Whenever you’re working on a plugin that’s going to have a decent set of options (and I’m not talking about giving users too much to think about because “decisions, not options,” remember?), it’s wise to initialize default WordPress options.
By that, I mean it’s important to set up an array or whatever data structure you like to use (but WordPress does love its arrays) and prepare them to be saved before the user even interacts with the settings page(s).
Think of it this way:
A user installs a plugin; they’ve yet to select any option; we need to drive the UI elements through input fields, checkboxes, radio buttons, etc., so we have functions that make calls into the database. But where they are they going to get their options?
That’s where this come into play.
Default WordPress Options
Remember that sometimes default options aren’t just unchecked boxes or empty input elements. Sometimes, there are things that we need to place. This can be driven by requires, our preferences, or some other external piece of information.
If it was a matter of initializing empty options, that’s no big deal because get_option
returns an empty string (which is a falsely value). But in the case of providing default options, I’m a fan of doing something like this:
- Set up a method that defines a multidimensional array with keys and values that have whatever settings you deem necessary.
- Merge this array with an empty array having a key that you’ll use to retrieve said options.
But there are some caveats to this.
On Querying The Options
If you plan to write more advanced queries around the options, I don’t necessarily recommend this approach because it will end up becoming costly.
For example, if you have a large collection of options and you’re going to need to be querying them throughout the application, it doesn’t make sense to load every option and then read them. Perhaps you could make a case for caching here, but even then, you’re loading a lot of unnecessary data.
I cover more about this in the primer on the options cache.
The point I’m ultimately trying to make is to be careful about how you structure your options.
Other Options For Options
I’m sure that the way I’ve laid this out is but one of many, so I’m curious how the rest of you opt to pursue this same problem.
Feel free to share gists, thoughts, comments, and questions below.
Leave a Reply
You must be logged in to post a comment.