ClassicPress Plugin Development: Load Multilevel Options with Defaults

ClassicPress PluginsThis post is part of the ClassicPress Plugin Development series in which I am going to look at both best practice for developing plugins and how I approach some requirements as well as some of the functions I commonly use.

Over the last couple of posts, I’ve taken a look at saving and loading options and how to load options with defaults. The defaults in the last post was a single dimension array, but you can also do the same with multi dimensional arrays using a ustom recursive parse of the arrays.

The below is an example of loading options with multi dimensional defaults from my Widget Announcements plugin:

/**
 * Get options including defaults.
 *
 * @since 1.1.0
 *
 */
function azrcrv_wa_get_option($option_name){
 
	$defaults = array(
						'widget' => array(
											'width' => 300,
											'height' => 300,
										),
						'to-twitter' => array(
												'integrate' => 0,
												'tweet' => 0,
												'retweet' => 0,
												'retweet-prefix' => 'ICYMI:',
												'tweet-format' => '%t %h',
												'tweet-time' => '10:00',
												'retweet-time' => '16:00',
												'use-featured-image' => 1,
											),
						'toggle-showhide' => array(
												'integrate' => 0,
											),
					);

	$options = get_option($option_name, $defaults);

	$options = azrcrv_wa_recursive_parse_args($options, $defaults);

	return $options;

}

/**
 * Recursively parse options to merge with defaults.
 *
 * @since 1.1.0
 *
 */
function azrcrv_wa_recursive_parse_args( $args, $defaults ) {
	$new_args = (array) $defaults;

	foreach ( $args as $key => $value ) {
		if ( is_array( $value ) && isset( $new_args[ $key ] ) ) {
			$new_args[ $key ] = azrcrv_wa_recursive_parse_args( $value, $new_args[ $key ] );
		}
		else {
			$new_args[ $key ] = $value;
		}
	}

	return $new_args;
}

Click to show/hide the ClassicPress Plugin Development Series Index