Adding And Updating Options In Wordpress

24th October 2008 - 3 minutes read time

Wordpress has an options table that developers can use when creating templates and plugins to store information that would otherwise have to be kept in a separate table or written to a file. Assuming the default table prefix of wp_ the options table is called wp_options.

Rather than allow developers to access this table directly, Wordpress has some functions that you can use to create and change options in that table.

To create an option and assign a null value to it use the add_option() function. The parameters are as follows:

  • name: The name of the option to be created.
  • value: The initial value of the option.
  • depcrecated: Optional. Not used (just add a '' to your code)
  • autoload: Optional. Should the option be automatically loaded on every page load? Valid values are yes or no, but the default is yes.
add_option( 'my_option' , '' );

If you want to create an option that does auto load then add a no at the end of the parameters.

add_option( 'my_option' , '' , '' , 'no');

To retrieve the value of an option you can use the get_option() function. This takes the name of the option and returns the value contained within the options table. Note that if you have set the option to auto load then this value will be generated from the option cache, otherwise it is generated via a database call.

get_option( 'my_option' );

To update an option you can use the update_option() function. The first parameter is the name of the function and the second is the new value of the option.

update_option( 'my_option' , 'my_value' );

To delete an option (for example, when you are deleting a plugin) use the delete_option() function. This takes the name of the option and deletes the option from the options table.

delete_option( 'my_option' );

One note to add is that you should be careful what you delete from this table as Wordpress uses a lot of it to generate pages and things. You can destroy your Wordpress install by deleting some of these values.

Add new comment

The content of this field is kept private and will not be shown publicly.