Multi-dimensional options array (for themes/plugins) with Settings API
-
I just figured this out and I thought I’d share it.
All the blog/forum posts on this topic are more than a year old. Either people have given up or I haven’t found the official post that explains how to do this. If there’s a more recent one out there, please share it with me.
NOTE: A few posts says to use
serialize()
andunserialize()
. You can but you don’t have to. There is an easier way. Read on.This is a generalized/simplified sample of how I store theme settings in a multidimensional array.
First, populate with some defaults. This step is optional but it shows you how I have an array within an array.
function set_default_theme_settings() { $meta = array ( 'date' => 1, 'category' => 1, 'author' => 1, 'comments' => 1 ); $options = array ( 'copyright' => 'blah blah blah', 'notfound' => 'yadda yadda yadda', 'meta' => $meta // This is the array within an array. ); add_option( 'blah', $options ); } add_action( 'after_theme_setup', 'set_default_theme_settings' );
blah
is the name of my theme (not in real life) and here I use it as the name of the option. Of course, changeblah
to something unique for your theme/plugin. Probably the name of your own theme or plugin.I won’t post all the code.
Cut a long story short, inside the form you pull out the options.
$options = get_option('blah');
Then you can use them like this:
<input type="text" name="blah[copyright]" value="<?php echo $options['copyright']; ?>" />
<input type="checkbox" id="meta_date" name="blah[meta][date]" value="1" <?php echo checked( 1, $options['meta']['date'], false ); ?> />
Take careful note of where to use
blah['…']
(for storing) and where to use$options['…']
(for retrieving).You can retrieve and store in the second array just by doubling up the square brackets…
options['meta']['date']
blah[meta][date]
And I assume you can bury data in endless depths of embedded arrays:
blah[program][department][section][project][methods][tools]…
This is basic PHP syntax, but for me the key was realizing that I could use this PHP syntax in the HTML input name attribute for saving to the options multi-dimensional array using the WordPress Settings API. And WordPress would handle it all for me. Sweet!
i.e.
name="blah[meta][date]"
That’s all folks! That’s all you need to do to retrieve and store settings in a multi-dimensional array in a single WordPress option.
P.S. If this is already common knowledge, please point me in the direction of some good references. I figured it out by trial and error, intuition and blunder.
- The topic ‘Multi-dimensional options array (for themes/plugins) with Settings API’ is closed to new replies.