Post Pic

How to: Use WordPress shortcodes with attributes

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.

14 Responses

Dec 22 2008 13:32

Is there a way to use this model and still be able to no-follow links? Or would you need to create two different functions?

Jan 01 2009 16:02

Hi Jean,

If I have function like this:

function myfunc($leftStr, $rightStr)
{
$returnStr = $leftStr.$rightStr;
return $returnStr;
}
add_shortcode(“func”, “myfunc”);

So in the post, how do I specify the syntax in this case?

Thanks.

Jun 13 2010 06:55

Is there a way to use the attributes from a shortcode in another function (not the shortcode function) for a plugin?

Jun 24 2010 15:09

Hi Jean,

Out of curiosity, is it usually considered a standard or best practice to set URLs, by default, to ‘http://’ when they are used as a ShortCode attribute (even thought this is obviously not a valid request)? For that matter, is it ever appropriate to include the PHP die() statement in a ShortCode function to reject bogus attribute inputs? Thanks!

-SD

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required