Remember to use the Shortcode API

The Shortcode API is an excellent way to embed HTML code in your posts and pages without much effort from the user.

In a recent project we had great use of the Shortcode API when we needed parts of our content styled inside a box. Simple enough for the shortcode!

We wanted something like

[box]
This content will be in a box!
[/box]

To be presented as:

<div class="box">
<p>This content will be in a box!</p>
</div>

To do so, just create a simple function and hook it up to the box shortcode (or any shortcode of your choice, just replace the first argument in the add_shortcode function). The function can take three arguments but I’m only using two. First one is $atts which is an array of the attributes and the second is $content which contains all the enclosed content.

function box_shortcode($atts, $content = null){
extract(shortcode_atts(array(
"class" => false
), $atts));

return "<div class=\"box" . ($class ? " " . $class : "" ) . "\">" . $content . "</div>";
}
add_shortcode("box", "box_shortcode");

While validating the HTML code I noticed that some wierd p tags sometimes appeared. So I got rid of them with two lines of code.

$content = preg_replace("/^<\/p>/", "", $content);
$content = preg_replace("/<p>$/", "", $content);

There you have it!

function box_shortcode($atts, $content = null){
extract(shortcode_atts(array(
"class" => false
), $atts));

$content = preg_replace("/^<\/p>/", "", $content);
$content = preg_replace("/<p>$/", "", $content);

return "<div class=\"box" . ($class ? " " . $class : "" ) . "\">" . $content . "</div>";
}
add_shortcode("box", "box_shortcode");

Besides boxes I’ve created formated v-cards, contact lists and much more with the Shortcode API. See the WordPress codex for more detailed information.

Advertisements
About

Web Developer @ Oakwood Creative - www.oakwood.se

Tagged with:
Posted in Intermediate

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

About

WordPress Quick Tips is a blog supplying great tips about WordPress.

We hope to create a great knowledge resource for WordPress developers as well as serving a reminder for all the forgetful ones.

The blog is created and run by Vincent of Oakwood Creative

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 120 other followers

%d bloggers like this: