admin管理员组

文章数量:1419666

How to add a default value to get_option if it's used as a variable ?

The code :

$my_options = get_option( 'my_options' ); // Associative Array 'my_options'.

<div id="identifier" class="classname" style="background-color: <?php 
echo esc_attr( $my_options['my_background_color_option'] ); ?>">

I want to avoid an Undefined index error or a false return.

Is the following correct ?

<div id="identifier" class="classname" style="background-color: <?php 
echo esc_attr( $my_options['my_background_color_option'] ) ? $my_options['my_background_color_option'] : '#000'; ?>">

How to add a default value to get_option if it's used as a variable ?

The code :

$my_options = get_option( 'my_options' ); // Associative Array 'my_options'.

<div id="identifier" class="classname" style="background-color: <?php 
echo esc_attr( $my_options['my_background_color_option'] ); ?>">

I want to avoid an Undefined index error or a false return.

Is the following correct ?

<div id="identifier" class="classname" style="background-color: <?php 
echo esc_attr( $my_options['my_background_color_option'] ) ? $my_options['my_background_color_option'] : '#000'; ?>">
Share Improve this question asked Jul 16, 2019 at 20:40 LebCitLebCit 2481 silver badge11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

So I originally suggested normalizing the options array; i.e. merging saved values with the default values. And this does solve the "undefined index" notice:

$my_options = wp_parse_args( get_option( 'my_options' ), [
    'my_background_color_option' => '#000',
    // ... other args.
] );

But to make sure that an option is not empty (e.g. not '', false, null, 0 or []), you can use empty() like so: (credits to this answer and yourself/OP)

<div id="identifier" class="classname" style="background-color: <?php echo esc_attr( // wrapped for clarity
    ( ! empty( $my_options['my_background_color_option'] ) ) ?
        $my_options['my_background_color_option'] : '#000'
); ?>">

There's also the array_merge(), but the above is indeed something that is good for validating an option. ( But sorry, I was focused on the "undefined index" thing and kinda forgot the (avoiding a) false return... =) )

本文标签: pluginsHow to add a default value to getoption if it39s used as a variable