Skip to content

Instantly share code, notes, and snippets.

@natejacobson
Created November 19, 2013 17:13
Show Gist options
  • Save natejacobson/7548847 to your computer and use it in GitHub Desktop.
Save natejacobson/7548847 to your computer and use it in GitHub Desktop.
Is there a way to do this with one command? Can I echo the specified array item without fetching the array first? These are coming from new customization options setup with $wp_customize. It is working, I'd just like to shorten.
<?php $spine_color = get_option( 'spine_theme_options' ); echo $spine_color['grid_style']; ?>
@jeremyfelt
Copy link

Nope, and I'd argue that making it longer would be better here for clarity.

<?php

$spine_color = get_option( 'spine_theme_options' );

if ( isset( $spine_color['grid_style'] ) ) {
    echo $spine_color['grid_style'];
} else {
    echo 'my-default-grid-style';
}

@jeremyfelt
Copy link

Also... if there are many of these array keys that need to be checked, it may be worth looking at wp_parse_args() - http://codex.wordpress.org/Function_Reference/wp_parse_args

<?php

$spine_defaults = array(
    'grid_style'   => 'my-default-grid-style',
    'other_thing' => 'other-value',
);

$spine_option = get_option( 'spine_theme_options', array() ); // default to an empty array if it doesn't exist

$spine_option = wp_parse_args( $spine_option, $spine_defaults ); // merges the defaults with the DB

echo $spine_option['grid_style']; // We know grid_style exists now.

@natejacobson
Copy link
Author

Come to think of it, $wp_customize does expect defaults to be set up, so that default will always be in place. For example,

$wp_customize->add_setting('spine_theme_options[spine_color]', array(
'default' => 'white',
'capability' => 'edit_theme_options',
'type' => 'option',

Which also means, I don't need to worry about the other call degrading gracefully, right?

@jeremyfelt
Copy link

It likely won't cause any issues, though it is best practice to continue checking. Data pulled from the database cannot be trusted in similar ways that data inputted by a user cannot be trusted. Operating under the assumption that it somehow disappeared would be good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment