Website development and design blog, tutorials and inspiration

Create Custom WordPress Shortcodes

By Tim Trott, 10th May 2014 in PHP

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 a action to a hook.

Let's first create the function that will handle our shortcode.

  1. function youtube_shortcode($atts, $content = null)
  2. {
  3. extract(shortcode_atts(array('id' => ''), $atts));
  4. return '<iframe width="640" height="360" src="http://www.youtube.com/embed/'.$id.'?feature=player_detailpage" frameborder="0" allowfullscreen></iframe>';
  5. }

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 in the parameters that the shortcode we want to create is called "youtube".

  1. add_shortcode('youtube', 'youtube_shortcode');

And that is about it for this basic example. I said it easy 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:

&#091;youtube id="{INSERT_ID_HERE}"&#093;

You can get the YouTube video ID from the URL in the address bar. It will look something like this:

How to Add YouTube Videos to Wordpress
How to Add YouTube Videos to Wordpress

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.

Comments

There are no comments for this post. Be the first!

Leave a Reply

Your email address will not be published.