9

Or how can I populate wordpress database with default plugin values, add option doesnt works for me, like http://codex.wordpress.org/Function_Reference/add_option

I am sure my syntax is correct, what I want is, when the user goes to the settings menu of my plugin, he/she doesn't see the blank input field, rather see it filled with default data.

WebDDelhi
  • 93
  • 1
  • 3

3 Answers3

8

https://developer.wordpress.org/reference/functions/add_option/ is a safest way to register option and also set a default value. It will only work if that option does not already exists in the options.

Ricardo Martins
  • 5,702
  • 3
  • 40
  • 59
thevikas
  • 1,618
  • 1
  • 14
  • 31
8

Just add the default values of your option(s) as the second parameter of the get_option() function call(s). Unless the option does not exists, this value will be returned then.

hakre
  • 193,403
  • 52
  • 435
  • 836
3

If you store plugin settings in an array like I do, passing defaults to get_option won't be enough if you change your settings in the future or add new keys to the array because the database value already exists and you defaults won't be loaded. Instead you could use a mix of get_option and wp_parse_args

For example check this bit of code:

    $defaults = array(
        'wsi_license_key'   => '',
    );
    $settings = wp_parse_args( get_option( 'wsi_settings', $defaults), $defaults );
chifliiiii
  • 2,231
  • 3
  • 28
  • 37