Creating Simple oEmbed-Based WordPress Shortcodes

/ Published in: PHP
Save to your folder(s)

Say you wanted to create a shortcode like this: [youtube id="991WcoEPwb8"]

And instead of manually creating the HTML yourself, you wanted to use YouTube’s oEmbed provider to get the HTML. While that’s easy to do using WordPress’ existing functions (wp_oembed_get() for example), you must implement your own caching of the result as WordPress’ oEmbed class does not include any caching of it’s own.

However, WordPress comes with an [embed] shortcode that’s also secretly used for the shortcode-less embeds. A cool trick is to make that shortcode’s existing code (complete with caching) work for you! This post explains how to do it.

Copy this code and paste it in your HTML
  1. add_shortcode( 'youtube', 'my_youtube_shortcode' );
  3. function my_youtube_shortcode( $atts ) {
  5. // We need to use the WP_Embed class instance
  6. global $wp_embed;
  8. // The "id" parameter is required
  9. if ( empty($atts['id']) )
  10. return '';
  12. // Construct the YouTube URL
  13. $url = '' . $atts['id'];
  15. // Run the URL through the handler.
  16. // This handler handles calling the oEmbed class
  17. // and more importantly will also do the caching!
  18. return $wp_embed->shortcode( $atts, $url );
  19. }


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.