3

Does Wordpress have a way to set a default value for an option?

That is -- I know get_option accepts a second parameter, and will return that parameter if no value is set. For example, when I'm setting up my form to let users save a value, I might use something like this

<td>
    <input type="text" 
           name="new_option_name" 
           value="<?php echo esc_attr( get_option('new_option_name','default') ); ?>" 
    />
</td>

If new_option_name doesn't have a saved value, get_option will return default.

However -- when I fetch the value in other places (i.e. I want to use the value), I need to specify the string again. This introduces the possibility of mistakes

$someOtherVariable = get_option('new_option_name','defaultt');

Other settings systems I've worked with give you the ability to configure a default value for settings that have not yet been saved. Does Wordpress have a feature like this? Or is it up to the end user programmers to make sure their get_option defaults match in all their code?

1
  • 1
    Sorry, nothing out of the box. What about a decorator function for get_option?
    – kraftner
    Aug 8, 2016 at 15:16

1 Answer 1

4

There isn't anything clever that I can see. I've used two approaches in the past:

1 - Your plugin's activation code could save all your default options, so that you never need to use the second parameter to get_option Really, this equates to your...

default value for setting that have not yet been saved.

2 - You could define a set of constants for the default values, and then use those constants for the second parameter to get_option

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.