How to set the default value of a option in a theme?

As @Ashfame as already pointed out, you shouldn’t store defaults in the database – that should be for user selected options (of course, if they select the defaults, then fine – store them :).

However, you don’t need to use wp_parse_args() either. get_option allows you to select a default value. For instance:

//If nuod_logo is not found, uses 'newlogo.pnp'
$number = get_option('nuod_logo', 'newlogo.png') 

However, often themes and plug-ins (as they should) keep their options in an array which is stored in one row in the database. So

$my_plugin_options = get_option('my_plugins_options') 

is expected to return all options. So you could keep all options in a default array $my_plugin_defaults:

$my_plugin_options = get_option('my_plugins_options',$my_plugin_defaults) 

but this isn’t great either – you have to redeclare $my_plugin_defaults which is simply duplicating code, making room for bugs, ugly – or you make it a global variable which is just plain wrong. The solution is to create your own ‘get_option‘ which builds on WordPress’ settings API:

 function wpse28954_get_option( $option_name="" ){

      $defaults = array(
          // Array of defaults: option => default value 
      )
      $options = get_option('my_plugins_options',$defaults);

      //Parse defaults again - see comments
      $options = wp_parse_args( $options, $defaults );

      if( !isset($options[$option_name]) )
           return false;

      return $options[$option_name];

 }

This could be improved by allow wpse28954_get_option to set a default value in case its not in the defined defaults

Now your defaults are stored in one, easy to manage place and you can use wpse28954_get_option['my-option'] to return the saved setting or else the default value.


Edit

AS @Ashfame has pointed out in the comments using wp_parse_args has the advantage of providing defaults for an unsaved subset of options. I’ve updated my answer to include this. (This makes the $defaults in get_option rather redundant). +1 for @Ashfame‘s solution which was first to suggest using wp_parse_args.

Leave a Comment