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.