How to: Use WordPress shortcodes with attributes

December 15, 2008 at 8:09 am

Some days ago, I shown you how to save time by using WordPress shortcodes. Do you know that WordPress shortcodes can handles attributes? Here’s a recipes about it.

Adding attributes to your shortcodes isn’t that hard. First, make sure that you have read and understand this recipe about creating shortcodes.

Paste the following code on the functions.php file from your theme.

function myUrl($atts, $content = null) {
	extract(shortcode_atts(array(
		"href" => 'http://'
	), $atts));
	return '<a href="'.$href.'">'.$content.'</a>';
}
add_shortcode("url", "myUrl");

As you can see on the above code, I have defined a default value for the href attribute on line 3. I’m using this value on the last line, as the value of the html href attribute.

When you’re writing a post/page, insert the following code in the html editor:

[url href="http://www.wprecipes.com"]WordPress recipes[/url]

It will display a link, titled WordPress recipes to http://www.wprecipes.com.