I like using WordPress post formats, especially for embedding audio and video. However, what I don’t like is that the only way to get the video, audio, or other piece of embedded media to show on your homepage and category pages is to output the entire content of the post.

So I fixed it.

How to get just the embedded media in a WordPress post excerpt

In your content.php file (or wherever your theme keeps its output for the post format in question), use the following code wherever you want to get your “rich excerpt”:

$content = get_the_content();
$content = apply_filters( 'the_content', $content );
$content = str_replace( ']]>', ']]>', $content );
$content = explode('</iframe>',$content);
if(sizeof($content) > 1){
     $content = $content[0];
     $content .= '</iframe>'; 
} else {
     $content = $content[0];
echo $content;

Essentially what this does is

  1. Grabs the content
  2. Tries to split the content up wherever an iframe is found
  3. If 1 or more iframes are found:
    1. Get everything up to the first iframe in $content
    2. Replace the missing </iframe> (which we lost when we exploded the content) on the end of $content
  4. Or If 0 iframes are found
    1. Get everything and put it in $content
  5. Output $content

This seems to be working in this blog’s current theme, Polymath.