Short Codes are everywhere; they are one of the main features that theme authors advertise, and they are tremendous tools for plugin developers.
Adding a short code to your plugin is quite simple, actually.
Take a look at the sample code below:
1 2 3 4 5 6 7 8 9 10 11 12 | function pippin_example_shortcode( $atts, $content = null) { extract( shortcode_atts( array( 'message' => '' ), $atts ) ); // this will display our message before the content of the shortcode return $message . ' ' . $content; } add_shortcode('example', 'pippin_example_shortcode'); |
This is just a very basic example, but it demonstrates at least 90% of everything you need to know about creating shortcodes.
The first step is to create a function that has two parameters: $atts, and $content = null. These allow us to pass options to our shortcode.
Second, we extract all of the short code parameters are store them into variables. In this case, our shortcode can accept a parameter called “message” that will be stored in a variable called $message.
Third, we return whatever is stored in $message and also the content of the shortcode.
Lastly, we use the add_shortcode() function to make the short code available for use in the editor.
It can be used like this:
[example message="Hello there!"]The message parameter will be prefixed to this content.[/example] |
Our result will look like this:
Hello there! The message parameter will be prefixed to this content.
Once you know the basics of shortcodes, your possibilities are nearly endless.
Pingback: Create an Ajaxified Contact Form Short Code | Pippin's Plugins
Awesome and quick tutorial. Is there any simple way to add created shortcodes to a button in the wordpress editor, so that if a user clicks it, the shortcode will echo in the editor?
A simple / quick way? No, not really. The process is a little complicated, but quite doable. I wrote a sample plugin that shows how to do it: https://pippinsplugins.com/user-friendly-short-codes-plugin-example/ At the bottom of that page is also a link to the tutorial covering the same topic on Pro Blog Design.
Awesome, quick and easy tutorial. Creating my first plugin today and proving a lot easier than I thought. The WordPress community rocks!
Congrats on building your first plugin! When I first started, I thought it would be a lot harder than it is too.
Still in 2014 helpful, thanks
Everything clear. But it’s 100% functional way. While my plugin is object oriented. So I had to put add_shortcode() inside __construct() of my class. .
thanks man
Great article, simple, but very helpful. Now I’m using https://wordpress.org/support/view/plugin-reviews/simple-text-shortcodes but will try to create my own plugin. Thank you