Rabbit

Tutorials

How to use the WordPress Options API

The Options API is a battle tested way of storing data in the WordPress database. Data is stored in the wp_options table and can be an integer, a string, an array or even an object. 4 CRUD functions perform the heavy lifting.

  • add_option()
  • get_option()
  • update_option()
  • delete_option()

Adding an option

add_option() accepts an option name and value and will create a new option if that option name doesn’t exist and isn’t a protected option name. At the time of writing protected names are “alloptions” and “notoptions”.

add_option( 'columns', 'three' )

The function will return false if the option wasn’t added and true if the option was added.

Getting an option

get_option() accepts an option name and a default value to return if the option doesn’t exist.

get_option( 'columns', 'two' )

If the option name doesn’t exist, the default value will be returned. false is used as the default value if a default value isn’t supplied in the get_option() call. The option value will be unserialised if necessary before it’s returned.

Updating an option

update_option() accepts an option name and a new value.

update_option( 'columns', 'six' )

If the option name doesn’t exist then add_option() will be used to create a new option. If the option name exists, the function will update the option’s value. true will be returned if the option value has changed and false will be returned if not.

Deleting an option

delete_option() accepts the name of the option to be deleted and will remove the option from the database if the option exists.

delete_option( 'columns' )

The function will return true if the operation was successful and false if not. false will also be returned if the option didn’t exist.

Multisite

If you’re running WordPress in network mode, 4 “_site_” functions can be used instead.

  • add_site_option()
  • get_site_option()
  • update_site_option()
  • delete_site_option()

These functions are essentially the same as their single-site counterparts but options will apply network wide.

Autoloading

Both add_option() and update_option() accept an autoload argument. This will determine if the option is loaded when WordPress starts.

Posted by on .

0 comments

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>