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
1 Answer
Reset to default 1So 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
版权声明:本文标题:plugins - How to add a default value to get_option if it's used as a variable? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745314473a2653086.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论