wp_parse_args() WordPress Function

The wp_parse_args() function is used to parse a string of arguments into an array. The function is useful for setting default values for a function or method.

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

Merges 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.


Top ↑

Parameters

$args

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

$defaults

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

Default value: array()


Top ↑

Return

(array) Merged user defined values with defaults.


Top ↑

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.


Top ↑

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;
}


Top ↑

Changelog

Changelog
VersionDescription
2.3.0$args can now also be an object.
2.2.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More