Spruce interactive

Noise

Add YouTube Videos & Other Media Embeds to the WordPress Excerpt

Posted: October 15th, 2012

Author: Ben Heller

Tags:

, , ,

 Details

We’re working on a WordPress theme that shows post excerpts in a grid on its homepage (see perlsteinlab.com or perlsteinlab.com). The problem is that don’t really dig using other third-party plugins. They inevitably introduce bugs and complexities to a theme, and limit its portability. At the end of the day, our goal is to make any edits to a theme in such a way that it can be transported to another install with no additional configuration. In this case, we want to check whether there’s video content associated with a post, and then display that video as a custom excerpt along with the usual text snippit.

In version 2.9, WordPress introduced the oEmbed method of including video content in posts. This is what allows you to simply paste http://www.youtube.com/watch?v=uWN0xM-i2I8 into a post without worrying about all that extra embed code. As a result, WordPress now stores the oEmbed ID as a custom field that can be accessed using get_post_custom(), get_post_custom_keys(), and get_post_custom_values(). This lets us loop through a post’s custom keys, pick out the ones that contain “oembed”, and then display the value for that particular key, which in this case is the video embed code.

// Use First Video as Excerpt
$postcustom = get_post_custom_keys();
if ($postcustom){
  $i = 1;
  foreach ($postcustom as $key){
    if (strpos($key,'oembed')){
      foreach (get_post_custom_values($key) as $video){
        if ($i == 1){
          $text = $video.$text;
        }
      $i++;
      }
    }  
  }
}

In plain English, what we’re doing is this: If a post has custom values, then loop through the array. If an array key contains the string “oembed”, then pull out the first instance of this and add its value (the video embed code) to our excerpt (here stored in the $text variable). All together, the function looks like this:

// Custom Excerpt
function custom_wp_trim_excerpt($text) {
  $raw_excerpt = $text;
  if ( '' == $text ) {
    $text = get_the_content(''); // Original Content
    $text = strip_shortcodes($text); // Minus Shortcodes
    $text = apply_filters('the_content', $text); // Filters
    $text = str_replace(']]>', ']]>', $text); // Replace
    
    $excerpt_length = apply_filters('excerpt_length', 55); // Length
    $excerpt_more = apply_filters('excerpt_more', ' ' . '<a class="readmore" href="'. get_permalink() .'">&raquo;</a>');
    $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    
    // Use First Video as Excerpt
    $postcustom = get_post_custom_keys();
    if ($postcustom){
      $i = 1;
      foreach ($postcustom as $key){
        if (strpos($key,'oembed')){
          foreach (get_post_custom_values($key) as $video){
            if ($i == 1){
              $text = $video.$text;
            }
          $i++;
          }
        }  
      }
    }
  }
  return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_wp_trim_excerpt');

Add this to your functions.php and your theme will be cookin’ with enriched media excerpts. Add video from YouTube, Vimeo, and more, just by pasting the URL into the post content. Remember that this code will always pick out the first video from any given post. If you’d like to modify it to show all videos, just remove the $i == 1 (and it’s pairing bracket) within the last foreach loop.

  • http://www.facebook.com/FluGan FluGan Jönsson

    It only works with vimeo videos for me. http://www.sideways.nu

  • Rolly Winters

    works well. Thanks!

  • Tom Phillips

    Great code, thanks. Any thoughts on how would you change the height and width of the video using this code?

    • spruceit

      Hi Tom,

      I think that’s another bag altogether! We’d probably opt to use jQuery for that task, though we mostly use fitvids.js (http://fitvidsjs.com/) these days for responsive video embeds. Suggestion definitely noted, so maybe we’ll write a follow-up someday.

  • George sprouse

    Thanks for the code! Any way to let it display other embeds such as instagram. Right now the code produces an error “{{Unknown}}” in the post with the instagram embed

    • spruceit

      Hi George! Could you provide us with an example of the Instagram embed code you’re using? We’ll look into adapting to code to suit your example, and possibly a much broader range of embeds. Thanks!

  • Katrina Moody

    I’m working on a customized version of the Twenty Thirteen theme and trying to customize the post format display on the index page, where I’ve pulled excerpts. I got this working so that the video displays (yay!) BUT I was wondering if there might be a way to take this just a little bit further, using the idea – to display the first oEmbed – to instead display the video above the title (for an example – on the image posts I display the featured image above the title and was able to specify that it in the image-content.php.) … would it be possible to use the function to instead display the oEmbed by outputting it outside the excerpt and separately – so I could then display it above the title?

    This is so helpful, in any case, thanks so much for posting it!

  • Tomas B

    It’s pretty messy. The videos have different size with each post and the text is pinned right after them. Any way to modify this to actually give it some div with css styling so we can control the placement?

  • david

    thanks for the great code!!!!!
    …..one thing….

    this is working locally on my machine using mamp.

    when i upload my theme to the real internet the video stops showing up in excerpt…

    any ideas?

  • Tomas Espinoza

    Thanks for the help.

  • Arnel Delusa

    great tutorial. Is there anyway we can make the title of the video hide? like adding this tags rel=0&fs=0&autohide=1&showinfo=0&controls=0&hd=1&feature=oembed into the youtube URL? i tried adding the tag in the post but the excerpt is still showing the titles.

Talk to Us

Wise men have said, "All good things must come to an end", and so it was with Spruce. We began our first project in 2006, and completed our last in Fall 2013. It's been a wonderful experience, but now it's time to begin the next adventure.

Though...we wouldn't want to leave you hanging, now would we? Here are our top recommendations for world-class branding, design, and web development:

  • Kristina (KJ) Parish and Beam Collective:
    KJ provided the artistic vision that allowed Spruce to succeed, and we still think she's the greatest designer in the entire world. She's started a new collective with some talented developers, and is covering much the same territory as Spruce--design and development all under one roof, with a caliber of service and professionalism seldom seen in this business or any other. If you like what you see on the Spruce site, then definitely get in touch with KJ at kj@beamcollective.com
  • Permanent Art & Design
    Permanent is a nationally recognized design & branding firm out of Minneapolis, MN. They've been a long term collaborator and strategic partner over the past couple years, and we'd recommend them for medium to large sized businesses/organizations who are serious about putting their best foot forward. In addition to design, Permanent offers strategy and marketing services, plus in-house and networked developers. For more information contact Joseph Belk joseph@permanentadg.com
  • Nate Thompson
    A freelancer, Nate reminds us of ourselves back in the day. Smart, communicative, and skilled, Nate is our recommendation for small to medium sized businesses/organizations who have sites built on Wordpress or other open source content management solutions. With a background in both design and development, he's a one-stop shop for most web-related tasks. You can get in touch at nate.a.thompson@gmail.com
  • Kevin DeBernardi
    Designer turned developer, Kevin is embarking on a freelance web career after working as the in-house designer at the Museum of the City of New York. He's adept at translating his design ideas into custom PHP code, and is constantly expanding his technical palette. Kevin's a good choice for projects that don't quite fit into the Wordpress mold, and that would benefit from a consistency of presence and vision from design through execution. Kevin can be reached at kevin@analoglifestyle.com