函数文档

wp_parse_args()

💡 云策文档标注

概述

wp_parse_args() 是 WordPress 核心函数,用于将用户定义的参数与默认数组合并,支持数组、对象或查询字符串作为输入。它广泛应用于 WordPress 内部,简化参数处理逻辑,提供稳定的参数传递模式。

关键要点

  • 函数接受两个参数:$args(必需,可以是字符串、数组或对象)和 $defaults(可选,默认值为空数组),返回合并后的数组。
  • 主要用途是避免在函数调用中处理默认值和输入参数的复杂性,允许函数通过 $args 参数灵活扩展可传递的值。
  • 常见应用场景包括 query_posts、wp_list_comments、get_terms 等函数,以及许多核心类和 API 中。
  • 从 WordPress 2.2.0 版本引入,2.3.0 版本起 $args 支持对象类型。

代码示例

function wpdocs_my_function( $args ) {
  $defaults = array(
    'name' => 'Mr. nobody',
    'favorite_color' => 'unknown',
    'age' => 'unknown',
  );
  $args = wp_parse_args( $args, $defaults );
  print_r( $args );
}

$args = array( 'age' => 36 );
wpdocs_my_function( $args );
// 输出:Array( 'name' => 'Mr. nobody', 'favorite_color' => 'unknown', 'age' => 36 )

注意事项

  • wp_parse_args() 不会递归合并数组;如果需要递归合并,需自定义函数实现。
  • 用户贡献笔记中提供了递归合并数组的示例函数 wpdocs_recursive_parse_args,可供参考。
  • 注意函数内部使用 array_merge(),$defaults 数组中的值会被 $args 覆盖,顺序为 $defaults 在前。

📄 原文内容

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.

Parameters

$argsstring|array|objectrequired
Value to merge with $defaults.
$defaultsarrayoptional
Array that serves as the defaults.

Default: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

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.

User Contributed Notes

  1. Skip to note 5 content

    Basic usage:

    function wpdocs_my_function( $args ) {
    
      $defaults = array(
        'name' => 'Mr. nobody',
        'favorite_color' => 'unknown',
        'age' => 'unknown',
      );
    
      $args = wp_parse_args( $args, $defaults );
    
      print_r( $args );
    
    }
    
    $args = array( 'age' => 36 );
    wpdocs_my_function( $args );
    
    // Output:
    // 
    // Array(
    //   'name' => 'Mr. nobody',
    //   'favorite_color' => 'unknown',
    //   'age' => 36,
    // )

  2. Skip to note 6 content

    Below is an example function using the wp_parse_args system to manage its single $args argument, which could be given whatever values you wanted.
    In this case $args stores detailed display overrides, a pattern found in many WordPress functions.

    /**
     * Define a new function that uses $args and wp_parse_args()
     */
    function wpdocs_explain_parse_args( $args ) {
    	$defaults = array (
    		'text' => 'wp_parse_args() merges $args into $defaults',
    		'before' => "<p>",
    		'after' => "</p> n",
     		'echo' => TRUE
    	);
    	
    	// Parse incoming $args into an array and merge it with $defaults
    	$args = wp_parse_args( $args, $defaults );
    	
    	$output = $args['before'] . $args['text'] . $args['after'];
    	
    	if (!$echo) 
    		return $output;
    	
    	echo $output;
    }
    
    /**
     * Run our new function using the defaults (no $args)
     * This would print out: 
     * 	<p>wp_parse_args() merges $args into $defaults</p>
     */
    wpdocs_explain_parse_args();
    
    /**
     * Run the function with some options overridden with an array
     * This would echo the output with the modified text and before arguments:
     * 	<p class='specialclass'>A better explanation</p>
     */
    wpdocs_explain_parse_args( array (
    	'text' => "A better explanation",
    	'before' => "<p class='specialclass'>"
    ) );
    
    /**
     * We can also pass in URL-style string-query and it will be converted
     * This would set $args['echo'] to 1 and $args['text'] to 0	
     */
    wpdocs_explain_parse_args( 'echo=1&text;=0' );

  3. Skip to note 8 content

    If you are looking to recursively merge two arrays, here is the function:

    if ( ! function_exists( 'wpdocs_recursive_parse_args' ) ) {
    	function wpdocs_recursive_parse_args( $args, $defaults ) {
    		$new_args = (array) $defaults;
    
    		foreach ( $args as $key => $value ) {
    			if ( is_array( $value ) && isset( $new_args[ $key ] ) ) {
    				$new_args[ $key ] = wpdocs_recursive_parse_args( $value, $new_args[ $key ] );
    			}
    			else {
    				$new_args[ $key ] = $value;
    			}
    		}
    
    		return $new_args;
    	}
    }

    Test case:

    $defaults = [
    	'x1' => 'level1',
    	'x2' => [
    		'a1' => 'level1',
    		'a2' => 'level1',
    	],
    	'x4' => [
    		'b1' => [
    			'c1' => 'level1',
    		],
    		'b2' => 'level1',
    	],
    	'x3' => 'level1',
    ];
    $args     = [
    	'x3' => 'level2',
    	'x2' => [
    		'a2' => 'level2',
    	],
    	'x4' => [
    		'b1' => [
    			'c1' => 'level2',
    			'c2' => 'leve2',
    			'c3' => [
    				'd1' => [
    					'e1' => 'ok',
    				],
    			],
    		],
    	],
    ];
    
    print_r( awps_recursive_parse_args( $args, $defaults );
    
    /**
     * Result
     */
    /*
    [
    	'x1' => 'level1',
    	'x2' => [
    		'a1' => 'level1',
    		'a2' => 'level2',
    	],
    	'x4' => [
    		'b1' => [
    			'c1' => 'level2',
    			'c2' => 'leve2',
    			'c3' => [
    				'd1' => [
    					'e1' => 'ok',
    				],
    			],
    		],
    		'b2' => 'level1',
    	],
    	'x3' => 'level2',
    ];
    */