W3cubDocs

/WordPress

wp_parse_args( string|array|object $args, array $defaults = array() )

Merge user defined arguments into defaults array.

Description

This function is used throughout WordPress to allow for both string or array to be merged into another array.

Parameters

$args

(string|array|object) (Required) Value to merge with $defaults.

$defaults

(array) (Optional) Array that serves as the defaults.

Default value: array()

Return

(array) Merged user defined values with defaults.

More Information

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.

Source

File: wp-includes/functions.php

function wp_parse_args( $args, $defaults = array() ) {
	if ( is_object( $args ) ) {
		$parsed_args = get_object_vars( $args );
	} elseif ( is_array( $args ) ) {
		$parsed_args =& $args;
	} else {
		wp_parse_str( $args, $parsed_args );
	}

	if ( is_array( $defaults ) && $defaults ) {
		return array_merge( $defaults, $parsed_args );
	}
	return $parsed_args;
}

Changelog

Version Description
2.3.0 $args can now also be an object.
2.2.0 Introduced.

© 2003–2019 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/wp_parse_args