Tim TrottTim TrottDon't quit

Create Custom WordPress Shortcodes

By , Saturday 10th May 2014 in WordPress

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.

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 in 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 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:

[youtube id="{INSERT_ID_HERE}"]

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.

My website and its content are free to use without the clutter of adverts, tracking cookies, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

About the Author

Tim Trott

Tim is a professional software engineer, designer, photographer and astronomer from the United Kingdom. You can follow him on Twitter to get the latest updates.

Further Reading
Leave a Reply

Your email address will not be published.