0

I have a custom theme option that allows the changing of logos. There are 3 logo options: option1, option2, and option3.

Upon theme activation, the default "option1" logo appears, but above it I get a "Notice: Undefined index: flagship_sub_shield in...". This error goes away if I save my custom theme option page.

Is there something wrong with how I'm writing my conditional? Or is the issue probably more with the theme-options.php file?

My code in header.php is

<?php
$theme_option = flagship_sub_get_global_options();
$shield = $theme_option['flagship_sub_shield'];

if ('option2' === $shield): 

  //Image Option #2

elseif ('option3' === $shield): 
   //Image Option #3

else: 
  //Image Option #1
endif; ?>

The flagship_sub_get_global_options function is located in my theme-options.php file, in my library directory. The relevant option is:

$options[21] =
array(
    'section' => 'select_section',
    'id'      => FLAGSHIP_SUB_SHORTNAME . '_shield',
    'title'   => __( 'Shield', 'flagship_sub_textdomain' ),
    'desc'    => __( 'Which shield should appear in the header?', 'flagship_sub_textdomain' ),
    'type'    => 'select',
    'choices' => array('option1','option2','option3'),
    'std'     => 'option1',
);

Any help is appreciated!

1 Answer 1

1

You could make sure the index is defined before accessing it in header.php, and fallback gracefully:

<?php
$theme_option = flagship_sub_get_global_options();
if ( array_key_exists( 'flagship_sub_shield', $theme_option ) ) {
    $shield = $theme_option['flagship_sub_shield'];
} else {
    $shield = 'option1'; // Default value
}

if ('option2' === $shield): 

  //Image Option #2

elseif ('option3' === $shield): 
   //Image Option #3

else: 
  //Image Option #1
endif; ?>

Another possibly better option - to avoid having to include this check everytime you are getting a setting from $theme_option - would be to review your flagship_sub_get_global_options() function and make sure it returns an array that includes every setting, including default values for those settings that are not saved in the database yet.

2
  • 2
    in_array is only for checking the values. Use array_key_exists() or isset() to check if the key exists.
    – Wilco
    Aug 9, 2018 at 14:19
  • Nice catch, I guess I was distracted. Updating my answer, thanks!
    – Iceable
    Aug 9, 2018 at 14:22

Your Answer

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

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