WordPress Settings API error

I believe the underlying problem is that the option array keys don’t exist yet. Let’s start here, in your initialization function:

if( false == get_option( 'thanathos_theme_display_options' ) ) {    
    add_option( 'thanathos_theme_display_options' );  
} 

First, this:

false == get_option( 'thanathos_theme_display_options' )

…should be this:

false === get_option( 'thanathos_theme_display_options' )

…because you’re expecting an array to be returned.

Second, this:

add_option( 'thanathos_theme_display_options' );

…should be this:

add_option( 'thanathos_theme_display_options', $defaults );

…where $defaults is a defined array of default values. As it is currently, you’re simply adding an empty row to the wp_options DB table, since you’re not telling add_action() what values to add to your option.

While we’re on the topic, I’ll mention that there’s a much better approach than adding default values to the DB. Instead of doing that, do something like this when you need to reference the Theme options:

function thanathos_get_options() {
    $defaults = array(); // define this somewhere; reference it here
    return array_merge( $defaults, get_option( 'thanathos_theme_display_options', array() ) );
}

This function will return any user-set options, while falling back to the Theme-defined defaults if the user hasn’t set any options.

So for example, in your settings page form field:

// Get Theme Options
$options = thanathos_get_options();
// Define form-field markup
 $html="<input type="checkbox" id="show_header" name="thanathos_theme_display_options[show_header]" value="1" " . checked(1, $options['show_header'], false) . '/>';

Now, even if the user hasn’t set a value for 'show_header', $options['show_header'] will return the Theme-defined default value, rather than throwing an error for the array key not being set.

Leave a Comment