wp_parse_args is a generic utility for merging together an array of arguments and an array of default values. It can also be given a URL query type string which will be converted into an array (i.e. "id=5&status=draft").

It is used throughout WordPress to avoid having to worry about the logic of defaults and input, and produces a stable pattern for passing arguments around. Functions like query_posts, wp_list_comments and get_terms are common examples of the simplifying power of wp_parse_args.

Functions that have an $args based setting are able to infinitely expand the number of values that can potentially be passed into them, avoiding the annoyance of super-long function calls because there are too many arguments to keep track of, many of whose only function is to override usually-good defaults on rare occasions.

wp_parse_args() 描述


wp_parse_args() is used inside a function you are defining to process incoming arguments. Below is an example of how wp_parse_args() can merge an array of defaults with an array of mixed arguments.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/** * Define the array of defaults */ $defaults = array(	'type' => 'post',	'before' => "<p>",	'after' => "</p> ",	'echo' => TRUE);/** * Parse incoming $args into an array and merge it with $defaults */ $args = wp_parse_args( $args, $defaults );

wp_parse_args() 用法



(array/string) (必填) Query string or Array of mixed arguments that will override the values in $defaults.

默认值: None

Can be passed URL-query style

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

Or as an array definition

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
array( 'type' => 'post', 'posts_per_page' => 5, 'cat' => '1' )


(array) (必填) Array of default values that will be overridden by $args

默认值: None

wp_parse_args() 参数


添加于 版本: 2.2.0

wp_parse_args() 历史


wp_parse_args() 函数的代码位于 wp-includes/functions.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
 * Merge user defined arguments into defaults array.
 * This function is used throughout WordPress to allow for both string or array
 * to be merged into another array.
 * @since 2.2.0
 * @param string|array $args     Value to merge with $defaults
 * @param array        $defaults Optional. Array that serves as the defaults. Default empty.
 * @return array Merged user defined values with defaults.
function wp_parse_args( $args, $defaults = '' ) {
	if ( is_object( $args ) )
		$r = get_object_vars( $args );
	elseif ( is_array( $args ) )
		$r =& $args;
		wp_parse_str( $args, $r );

	if ( is_array( $defaults ) )
		return array_merge( $defaults, $r );
	return $r;

wp_parse_args() 源文件