wp_parse_args( string|array|object $args, array $defaults = array() ): array
- Since
- 2.2.0, 2.3.0
- Source
wp-includes/functions.php:4951
Combines a set of user supplied arguments with an array of defaults, accepting the input as an array, an object, or a query-string. Falls back to the object's own properties or the parsed string when no non-empty defaults array is supplied, and any keys already present in the input override the matching default. Common companion for shortcode and widget callbacks that need to fill in missing settings.
Description
This function is used throughout WordPress to allow for both string or array to be merged into another array.
Compatibility
- WordPress
- since 2.3.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$argsstring|array|object- Value to merge with $defaults.
$defaultsarrayoptional- Array that serves as the defaults.
Default empty array.Default:array()
Return value
array- Merged user defined values with defaults.
Code examples
Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
Merge shortcode-style query string arguments into default values
A block of code accepts arguments as a query string and needs sensible defaults for anything the caller omits.
$defaults = array(
'count' => 5,
'order' => 'DESC',
);
$args = wp_parse_args( 'count=2&order=ASC', $defaults );
$recent = get_posts( array(
'numberposts' => $args['count'],
'order' => $args['order'],
) );
foreach ( $recent as $recent_post ) {
echo esc_html( $recent_post->post_title ) . '<br>';
}The string form is parsed the same way as a URL query string, so keys must be plain ASCII names without spaces.
Fill in missing properties on a settings object
A theme reads customizer-style settings as a stdClass object where some properties may never have been set.
$settings = new stdClass();
$settings->per_page = 3;
$defaults = array(
'per_page' => 10,
'layout' => 'grid',
);
$parsed = wp_parse_args( $settings, $defaults );
printf(
'Layout: %s, Per page: %d',
esc_html( $parsed['layout'] ),
(int) $parsed['per_page']
);Common problems and fixes · 4
- Why does wp_parse_args not apply my defaults array?
- Why did my numerically indexed array get reindexed after calling wp_parse_args?
- What happens if I pass a raw query string instead of an array?
- Does wp_parse_args modify the array I passed in?
Why does wp_parse_args not apply my defaults array?
is_array( $defaults ) && $defaults). Pass an empty array, null, or a truthy non-array value and the function returns $args unchanged, no matter what $args contains.Why did my numerically indexed array get reindexed after calling wp_parse_args?
What happens if I pass a raw query string instead of an array?
Does wp_parse_args modify the array I passed in?
$parsed_args =& $args) before merging. The returned value is a new merged array, so the original variable in the caller is not changed by the merge itself.Alternatives and related functions
shortcode_atts- When you are writing a shortcode callback and want unknown attributes filtered out and a documented filter hook for extending the defaults.
wp_parse_str- When you only need to turn a query string into an array and do not need it merged with a set of defaults.
array_merge- When both inputs are already plain arrays and you do not need object or query-string support.
array_replace- When you need to preserve integer keys exactly as given instead of having them renumbered by the merge.
Performance profile
How much work a call to wp_parse_args() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Trivial
- Scaling
- Constant
- Instructions
- 11–18
- Plugin surface
- None
- Called by
- 50
Touches nothing outside its own arguments.
No loop in the body: the same number of instructions runs whatever you pass in.
Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 26.
Nothing here hands control to plugin code.
50 places in core call this, so the cost is paid more often than your own code shows.
What it touches
- hookthird-party callbacks
apply_filters()one call below wp_parse_args()
What one call costs · 6 distinct outcomes
One number would be a lie: the work depends on which branch runs. These are every distinct cost wp_parse_args() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
!is_object($args) && is_array($args) | 11–12 | none |
is_object($args) | 12–13 | get_object_vars() |
!is_object($args) && !is_array($args) | 13–14 | wp_parse_str() |
!is_object($args) && is_array($args) && is_array($defaults) | 16 | array_merge() |
is_object($args) && is_array($defaults) | 17 | get_object_vars(), array_merge() |
!is_object($args) && !is_array($args) && is_array($defaults) | 18 | wp_parse_str(), array_merge() |
Across PHP versions
Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 26 instructions, 11–18 executed per call, 4 branches. The work does not change between versions.
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Uses · 1
- wp_parse_str()Parses a string into variables to be stored in an array.
Used by · 50
- Bulk_Upgrader_Skin::__construct()Constructor.
- Core_Upgrader::upgrade()Upgrades WordPress core.
- Featured_Content::get_setting()Gets featured content settings.
- Language_Pack_Upgrader::bulk_upgrade()Upgrades several language packs at once.
- Language_Pack_Upgrader_Skin::__construct()Constructor.
- Plugin_Installer_Skin::__construct()Constructor.
- Plugin_Upgrader::bulk_upgrade()Upgrades several plugins at once.
- Plugin_Upgrader::install()Install a plugin package.
- Plugin_Upgrader::upgrade()Upgrades a plugin.
- Plugin_Upgrader_Skin::__construct()Constructor.
- Theme_Installer_Skin::__construct()Constructor.
- Theme_Upgrader::bulk_upgrade()Upgrades several themes at once.
Show all 50
- Theme_Upgrader::install()Install a theme package.
- Theme_Upgrader::upgrade()Upgrades a theme.
- Theme_Upgrader_Skin::__construct()Constructor.
- Twenty_Twenty_One_Dark_Mode::the_html()Prints the dark-mode switch HTML.
- WP_Ability::prepare_properties()Prepares and validates the properties used to instantiate the ability.
- WP_Admin_Bar::add_node()Adds a node to the menu.
- WP_Ajax_Response::add()Appends data to an XML response based on given arguments.
- WP_Block::render()Generates the render output for the block.
- WP_Block_Templates_Registry::get_by_query()Retrieves registered templates matching a query.
- WP_Block_Type::set_props()Sets block type properties.
- WP_Comment::get_children()Gets the children of a comment.
- WP_Comment_Query::parse_query()Parse arguments passed to the comment query with default query parameters.
- WP_Comment_Query::query()Sets up the WordPress query for retrieving comments.
- WP_Customize_Manager::validate_setting_values()Validates setting values.
- WP_Customize_Media_Control::__construct()Constructor.
- WP_Debug_Data::get_wp_plugins_raw_data()Gets the raw plugin data for the WordPress active and inactive sections of the debug data.
- WP_Embed::get_embed_handler_html()Returns embed HTML for a given URL from embed handlers.
- WP_Embed::shortcode()The do_shortcode() callback function.
- WP_Font_Collection::get_data()Retrieves the font collection data.
- WP_Font_Face::validate_font_face_declarations()Validates each font-face declaration (property and value pairing).
- WP_Font_Utils::get_font_face_slug()Generates a slug from font face properties, e.g. `open sans;normal;400;100%;U+0-10FFFF`
- WP_Http::get()Uses the GET HTTP method.
- WP_Http::head()Uses the HEAD HTTP method.
- WP_Http::post()Uses the POST HTTP method.
- WP_Http::request()Send an HTTP request to a URI.
- WP_Http_Curl::request()Send a HTTP request to a URI using cURL extension.
- WP_Http_Streams::request()Send a HTTP request to a URI using PHP Streams.
- WP_List_Table::__construct()Constructor.
- WP_List_Table::set_pagination_args()Sets all the necessary pagination arguments.
- WP_Network_Query::parse_query()Parses arguments passed to the network query with default query parameters.
- WP_Network_Query::query()Sets up the WordPress query for retrieving networks.
- WP_Plugins_List_Table::prepare_items()
- WP_Post_Type::set_props()Sets post type properties.
- WP_Query::parse_query()Parses a query string and sets query type booleans.
- WP_Query::query()Sets up the WordPress query by parsing query string.
- WP_REST_Block_Types_Controller::prepare_item_for_response()Prepares a block type object for serialization.
- WP_REST_Comments_Controller::check_is_comment_content_allowed()If empty comments are not allowed, checks if the provided comment content is not empty.
- WP_REST_Server::get_routes()Retrieves the route map.
Source code
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
Introduced in 2.2.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
$args can now also be an object.from the docblockAbout this page
- Parsed data
- Generated from the wordpress-develop 6.9.7 tag, from
src/wp-includes/functions.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.