Skip to content
Advertisement

WordPress – Add a default value to get_option if it’s used as a variable

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'; ?>">

Advertisement

Answer

As you’ve written it, you’re only catching Undefined Index errors. There’s also a parenthesis out of place that renders it syntactically meaningless. My opinion here is a ternary operator gets ugly with that much text. This would do exactly the same thing. You can always make things more elegant once you understand them.

<div id="identifier" class="classname" style="background-color: 
<?php
if (
  isset($my_options['my_background_color_option']) && 
  $my_options['my_background_color_option'] != FALSE
)
  {$op = $my_options['my_background_color_option'];}
else 
  {$op = '#000';}
echo esc_attr($op);
?>
">

Edit:

You could also use empty to achieve this in less words.

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

From there your ternary looks a little better:

<div id="identifier" class="classname" style="background-color: 
<?php
echo esc_attr((!empty($my_options['my_background_color_option']) ? $my_options['my_background_color_option'] : '#000')); 
?>
">
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement