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
… =) )