What does wp_parse_args do?

ggwicz picture ggwicz · Sep 11, 2011 · Viewed 10.6k times · Source

I've been building Wordpress widgets for a while and have always used some code like this:

$instance = wp_parse_args( (array) $instance);

It's never caused problems and is recommended in several places (by Justin Tadlock, two Wordpress books I have, etc.), but none of these sources really explain why.

So, what does this actually do, and what would happen if it was omitted?

Answer

SummaNerd picture SummaNerd · Aug 21, 2012

In layman's terms it's merging arrays.

It's used frequently because it allows a function to accept multiple arguments without making the code look messy. Then goes the next step by allowing the developer to set up default values.

That's where wp_parse_args comes in, it merges passed in values with defaults.

$args = wp_parse_args($passed_in_args, $default_values);

It also converts a URL query string into an array.

Hope this helps