Function argument arrays

DescriptionWordpress snippet by - 08/22/10

This is a reference function for dealing with function arguments in Wordpress easily, this is how most of their functions arguments are treated. You can pass arguments as a query string or as a pre made array. This makes assigning default values for the function arguments easier than writing the php conditionals and cleaner than stuffing all the defaults in the function arguments between the parenthesis. The wp_parse_arguments() function does most of the work for you.

Tags ,

<?php

//The function for your functions.php or plugin

function test_function($args = '') {
$defaults = array(
'arg1' => 'Default Value 1',
'arg2' => 'Default Value 2',
'arg3' => 'Default Value 3',
);

$r = wp_parse_args($args,$defaults);
extract($r);

echo "arg1 = $arg1<br>";
echo "arg2 = $arg2<br>";
echo "arg3 = $arg3<br>";
}

//Call the function using two techniques:

//1 - Using an array

$args = array(
'arg1' => 'Array Value 1',
'arg2' => 'Array Value 2',
'arg3' => 'Array Value 3',
);
test_function($args);

//2 - Using a query string

test_function('arg1=Query Value 1&arg2=Query Value 1&arg3=Query Value 3');
  • Share
Authored by: Adam J Nowak
http://hyperspatial.com

Comments and Feedback