WordPress shortcodes are very useful tools that allow developers to provide extra functionality to their theme / plugin users.
Shortcodes are often used for:
- Creating nicely-styled lists
- Embedding contact forms
- Displaying content in columns
- Including google maps in post content
- Applying extra styles to text and images
- Creating download buttons
- And anything else you can think of . . .
So let’s learn the very basics of how to create shortcodes for your plugin or theme.
First, a simple shortcode to display text (such as an author bio). Paste the code below into your functions.php or main plugin file:
1 2 3 4 | function bioText() { return 'The author is an experienced WordPres developer, blogger, and more. '; } add_shortcode('biotext', 'bioText'); |
You can now use [biotext] in your post content and it will be replaced with:
The author is an experienced WordPres developer, blogger, and more.
That’s a really, really, simple example, so let’s get a little more advanced now. This shortcode is almost exactly the same as the one above, except it let’s us define the text we want to be displayed.
1 2 3 4 | function bioText( $atts, $content = null ) { return '<div class="biotext">"'.$content.'"</div>'; } add_shortcode('biotext', 'bioText'); |
Now you’d use the shortcode like this:
[biotext]This is the text I want to display.[/biotext]
which will render as:
1 | <div class="biotext">This is the text I want to display.</div> |
Because our text gets wrapped in a DIV tag, we can style it any way that we want.
These are both simple examples, and we can get a lot more advanced. In follow up posts, I will demonstrate how to begin adding variables to your short codes.
For now, you might be interested in checking out some of these resources:
- http://net.tutsplus.com/tutorials/wordpress/wordpress-shortcodes-the-right-way/
- http://codex.wordpress.org/Shortcode_API
- http://www.problogdesign.com/wordpress/working-with-wordpress-shortcodes/
- http://pippinspages.com/freebies/wp-utility-short-codes-plugin-free/





