Creating Template Tags with Arguments

Your template tags can accept arguments in strings or arrays just like WP template tags do. The wp_parse_args() function is the key to WordPress's argument magic. This function takes in your arguments and converts them to an array if they aren't already. If you want, it can also merge your arguments with an array of default values. Then it passes the cleaned-up, merged array back to you for use in your template tag function.

You can use wp_parse_args() to provide a more flexible template tag that can override the settings you chose on the plugin options page. For example, let's extend the simple today() template tag. Perhaps you'd like to let the user specify a date format in the template tag, but use the stored option if no format is provided. You could also add an option to print some text before the date. Listing 9-3 shows the revised template tag function.

Listing 9-3. A today() template tag with arguments function today($args = '') {

$defaults = array('format' => get_option('date_format'), 'before' => '');

Now you can use the today() tag in either of the ways shown in Listing 9-4, and you'll get the date preceded by "Today is: ". If you don't provide any arguments, it will print the date without a prefix, using the formatting option chosen in Settings ^ General, just as it did before.

Listing 9-4. Using the new today() template tag

// arguments as a string today('format=l, M j, Y&before=Today is:');

// array would work too

// today(array('format' => 'l, M j, Y', 'before' => 'Today is:')); ?>

0 0

Post a comment