This post is part of the WordPress Plugin tutorial series. To find a link to all tutorials in order, then please click here.

In our previous tutorial, we learned about attributes. Our last shortcode took in 2 attributes, which were the link and the text, but it isn’t exactly the best idea to use the text attribute because what if the user is submitted paragraphs of text? Or even worse, what if they’re using quotes their message? Our solution, enclosing shortcodes.

WordPress allows us to create enclosing shortcodes, which is a combination of HTML and filter hooks. We’ll be working with the same plugin. Let’s update our post to this.

1

[jk link="http://jaskokoyn.com"]Like us on Facebook[/jk]

Enclosing Shortcodes

As you can see we threw out our text attribute and instead inserted our text after the [jk] shortcode and closed it with [/jk] closing shortcode. This makes our post look cleaner and easier to edit. Next, let’s update our function.

1

2

3

4

5

6

7

<?php

functionjk_WPSCEX_add_message($atts,$content=null)

{

$output='<a href="'.$atts['link'].'">'.$content.'</a>';

return$output;

}

?>

Our function now has a 2nd parameter. The $content variable will contain the content placed between the two tags. We set this to null just in case our users forget to put content in between the tags.

We then replace the $atts[‘text’] variable with the $content variable. This makes our code cleaner and you should be able to see the result. Update your post and take a look. Now, your users can input paragraphs of text and use quotes freely. They can use break lines and different styles. They can also places images and embed videos. Shortcodes are a powerful tool to use in your plugin with the flexibility you can provide to your users.

Enclosing Shortcodes

Conclusion

This concludes our discussion of shortcodes. We’ll take a deeper look into them once we go deeper into WordPress plugin development. If you would like to learn more information about enclosing shortcodes, go here.