WordPress wp_parse_args(): Merge Function Arguments with Defaults and Recursive Deep Merge

wp_parse_args(): merge arguments with defaults

Functions with many options take one $args array instead of a long list of parameters: WP_Query, wp_nav_menu(), wp_list_comments() all work that way. The caller passes only what differs from the defaults, and inside the function wp_parse_args() fills in the rest. Your own functions, shortcodes and widgets can use the same pattern.

Problem: A function that prints a list of posts has six options, callers pass only some of them, sometimes as an array and sometimes as a query string, and the nested query options get lost when only one of them is passed.

Solution: Merge the caller’s arguments with a defaults array using wp_parse_args( $args, $defaults ), merge nested arrays with a second call, and cast or validate the merged values before using them.

The basics

<?php
function ha_post_list( $args = array() ) {
    $defaults = array(
        'title'      => __( 'Latest posts', 'textdomain' ),
        'count'      => 5,
        'show_date'  => true,
        'query_args' => array(
            'post_type' => 'post',
            'orderby'   => 'date',
            'order'     => 'DESC',
        ),
    );

    $args = wp_parse_args( $args, $defaults );
    $args['query_args'] = wp_parse_args( $args['query_args'], $defaults['query_args'] );

    $query = new WP_Query( array_merge( $args['query_args'], array(
        'posts_per_page' => absint( $args['count'] ),
        'no_found_rows'  => true,
    ) ) );

    // ... print $args['title'] and the posts ...
}

ha_post_list( array( 'count' => 3 ) );
ha_post_list( 'count=3&show_date=0' ); // a query string works too
ha_post_list( array( 'query_args' => array( 'post_type' => 'event' ) ) ); // orderby and order stay

wp_parse_args() accepts an array, a query string or an object, and returns an array in which the caller’s values replace the defaults key by key.

Nested arrays

The merge works only on the top level. Without the second call, array( 'query_args' => array( 'post_type' => 'event' ) ) would replace the whole nested array, and orderby and order would be gone. Merge each nested array you expect explicitly, as above.

Values are not validated

<?php
$args = wp_parse_args( 'count=abc&show_date=0', $defaults );
// $args['count'] is "abc", $args['show_date'] is "0" (a string)

Values from a query string are strings, and the function does not check types. Cast or validate after merging: absint() for numbers, wp_validate_boolean() for flags (it understands "0", "false", "no"), in_array() with a list for options with fixed values.

Shortcodes: shortcode_atts()

For shortcodes, shortcode_atts() does the same and more: it drops attributes that are not in the defaults, and it lets other code change the result through the shortcode_atts_{shortcode} filter:

<?php
add_shortcode( 'ha_posts', function ( $atts ) {
    $atts = shortcode_atts( array( 'count' => 5, 'type' => 'post' ), $atts, 'ha_posts' );
    ob_start();
    ha_post_list( array( 'count' => absint( $atts['count'] ), 'query_args' => array( 'post_type' => sanitize_key( $atts['type'] ) ) ) );
    return ob_get_clean();
} );

Letting others change the defaults

<?php
$defaults = apply_filters( 'ha_post_list_defaults', $defaults );
$args     = wp_parse_args( $args, $defaults );

A filter on the defaults lets a theme change, for example, the default number of posts everywhere, without touching every call.

NOTE: Document the accepted keys and their defaults in the function’s docblock. A function with an $args array is flexible but opaque: without documentation, every caller has to read the code to know what can be passed.