- The basic OOP code structure of a WordPress Plugin – #1
- Creating default options on your WordPress Plugin Installation – Options API #2
So, this is the part two of our WordPress Plugin series. Previously we have given an overview on how to code your WordPress Plugin in proper OOP. We have seen the basics of the loader class and concept of the admin and installation class. This and the next tutorial is all going to be about the installation class. We have said that it was meant to be fired once, when are to install our plugin. But in this tutorial, we shall see how to have a method for reseting the options and databases as well. Something like “Master Reset“. So let us get into it.
#1: Understanding the Options API:
WordPress gives us a fantastic and robust method to store our set of options inside database without actually interacting with it directly. I believe this is one of the finest level of abstraction WordPress API has. With the help of this, we can store whatever value we want inside the database. Be it an array, an object, or some primitive datatypes like integers, string, float or whatever. Let us see how we can do this.
#1.1: Understanding add_option API:
Say, you have a set of options stored inside an array. Now you want to save the option for future use. In a normal case, we could’ve serialized that array and stored it in a database table. Well, WordPress, being one of the most excellent CMS, does this automatically for us. Let us see the function prototype:
function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' ) {/**/}
So, it accepts four arguments.
- $option – (String) : The name or key of the option. This should be unique and should not conflict with reserved names by WordPress.
- $value – (Mixed) : The value which you intend to store. Can be anything, array, simple string, int, object etc.
- $deprecated – (Mixed) : Deprecated. It used to be description, but not used anymore. We can pass an empty string if we want to use the next argument. (Optional)
- $autoload – (Boolean) : Whether to load and cache the option when WordPress startup. True by default. (Optional)
and returns true if option was successfully updated and false otherwise.
In practice, we just need to pass in two parameters $option and $value. Later on we can get it using the get_option API.
#1.2: Understanding get_option API:
It is just the complimentary part of add_option, which is used to get the original data from the saved value. Note that, it automatically returns the original datatype. So we do not need to unserialize it.
The function prototype is as follows:
function get_option( $option, $default = false ) {/**/}
It has two arguments:
- $option – (String) : The name or key of the option. This should be unique and should be same as we have used on the add_option API.
- $default – (Mixed) : The default value which should be returned if the option does not exist. false by default (Optional).
It returns either Mixed values (the original saved option value) or false if it does not exist and no other default is passed.
#1.3: Understanding update_option API:
As the same suggests, it updates an existing option to the new value. Also, if the option does not exist, then it is created.
The function prototype is:
function update_option( $option, $newvalue ) {/**/}
So as obvious it has two arguments (The first two arguments of add_option API):
- $option – (String) : The name or key of the option. This should be unique and should not conflict with reserved names by WordPress.
- $value – (Mixed) : The value which you intend to store. Can be anything, array, simple string, int, object etc.
It returns true if the option was updated. If the option does not require any update (i.e, if the passed value does not differ from the stored value or in case of some error) then false is returned.
#1.4: Understanding delete_option API:
As obvious, it simply deletes an option from the database. The prototype is:
function delete_option( $option ) {/**/}
The only accepted argument is:
- $option – (String) : The name or key of the option. This should be unique and should not conflict with reserved names by WordPress.
So it checks for protected options and safely deletes options created by plugins, themes etc. It returns true on success and false on failure.
#1.5: Further understanding:
These 4 APIs will be all that you will need to do most with the static options (creating, updating, deleting, retrieving etc). But if you wish to study further with the options API, have a look inside the /wp-includes/options.php file of the WordPress Source Code.
Food for thought:
Check the add_site_option and related APIs.
#2: Using Options API during plugin installation:
To start with, we shall create a method which does two basic things:
- Checks if the option is already present or not (i.e, whether the plugin was previously installed).
- Add the default set of option if it is not present.
#2.1: The basic installation method:
A basic method for a simple option addition during plugin installation would be:
/** * Creates the options */ private function checkop() { //check if option is already present //option key is plugin_abbr_op, but can be anything unique if(!get_option('plugin_abbr_op')) { //not present, so add $op = array( 'key' => 'value', ); add_option('plugin_abbr_op', $op); } }
As we have named this method checkop so the way of calling it through the public function install would be:
/** * install * Do the things */ public function install() { $this->checkop(); }
Now it corresponds to the activation hook method of the previously discussed main load method. With our structure of the class, whatever we are willing to do during the installation, it should be done through the public method install. So that, in the main loader class, only one method of the installation class needs to fire up.
#2.2: A practical example of installation:
Let us consider an example, where we would do the following things:
- Show a Twitter twit this buttons along with twitter follow button.
- Show Facebook like button for the current post/page along with like button for a particular facebook page.
- Show Google+ share button, along with follow button.
If we wish to make our plugin flexible, then of course we need to get user options and store them. We can simply use the Options API for this. A simplified method would be:
/** * Creates the options */ private function checkop() { //the default options $social_share_op = array( 'twitter' => array( 'enabled' => true, 'username' => '', ), 'facebook' => array( 'enabled' => true, 'page_id' => '', ), 'gplus' => array( 'enabled' => true, 'page_id' => '', ), ); //check to see if present already if(!get_option('social_share_op')) { //option not found, add new add_option('social_share_op', $social_share_op); } else { //option already in the database //so we get the stored value and merge it with default $old_op = get_option('social_share_op'); $social_share_op = wp_parse_args($old_op, $social_share_op); //update it update_option('social_share_op', $social_share_op); } }
Read the comments to know which step is doing what. In short, we have first checked whether the option is present or not. If not present then we have simply added it, and if present then we have got the old option, merged with the defaults and updated the stored values. This is a basic behaviour which we follow during most of the plugin installation.
#3: Giving provision for master reset:
Although the install-class is mainly intended to be used only during the plugin activation, but we shall do a bit more here. We shall provide a public method using which we can delete the stored option and restore it to its original value. The usage will entirely depend upon admin-class.php classes, but we shall here see the method itself.
/** * Restores the WP Options to the defaults * Deletes the default options set and calls checkop */ public function restore_op() { delete_option('plugin_abbr_op'); $this->checkop(); }
#4: Put together the class:
So, we have seen the installer method, the hooking method and the master reset method. Now we simply combine the method to write our class.
<?php /** * install-classes * The library of all the installation class * @author Swashata <swashata4u@gmail.com> * @package <Plugin Name> Plugin * @subpackage Installation Class * @version <Version> */ class itgdb_plugin_abbr_admin_install { /** * install * Do the things */ public function install() { $this->checkop(); } /** * Restores the WP Options to the defaults * Deletes the default options set and calls checkop */ public function restore_op() { delete_option('plugin_abbr_op'); $this->checkop(); } /** * Creates the options */ private function checkop() { //check if option is already present //option key is plugin_abbr_op, but can be anything unique if(!get_option('plugin_abbr_op')) { //not present, so add $op = array( 'key' => 'value', ); add_option('plugin_abbr_op', $op); } } }
#5: Conclusion:
Obviously you will need to write the checkop method the way it suits your need. The codes given here are just examples and help you get started. We shall see more on the implementation when we move to the loader class.
So that was all about the WordPress Options API and using it for creating default options during your plugin installation. On the next post of this series, we shall see how to create databases during installation. If you have any doubt or question, feel free to ask.
“On the next post of this series, we shall see how to create databases during installation.”
Too bad we have to wait so long 😉