Create Custom WordPress Shortcodes
WordPress Shortcodes are a great way to add dynamic content to posts, even for non-techy editors, and can be as simple or as complex as you require.
I'm going to start off with a very basic WordPress shortcode, one that is very easy to implement. It will display a YouTube video in the post, inline.
This code should go in your functions.php or plugin file.
Shortcodes are added to WordPress by adding an action to the list of shortcodes. This is done using the
add_shortcode function in much the same way as you add an action to a hook.
Let's first create the function that will handle our shortcode.
- function youtube_shortcode($atts, $content = null)
- extract(shortcode_atts(array('id' => ''), $atts));
- return '<iframe width="640" height="360" src="http://www.youtube.com/embed/'.$id.'?feature=player_detailpage" frameborder="0" allowfullscreen></iframe>';
This function is going to create a string that contains the embed YouTube code (taken from the YouTube site) and it will replace the video ID with the PHP variable $id. The $id variable gets its value from the shortcode attribute id. Shortcodes must always return the value, not echo it.
Now, lets call the add_shortcode function, specifying the parameters that the shortcode we want to create is called "youtube".
- add_shortcode('youtube', 'youtube_shortcode');
And that is about it for this basic example. I said it easy! To use this shortcode once it is added to the file, simply create a post (or edit an existing one) and add the shortcode to the content:
You can get the YouTube video ID from the URL in the address bar. It will look something like this:
When you view the post, this code will be replaced with the HTML in the youtube_shortcode function and you will hopefully see the YouTube video.
You can also add buttons to the shortcode in the editor to make it even easier. There is a great tutorial on WP Tuts+, so I don't think I need to explain it again here.