Add oEmbed to Post Meta Data in WordPress

WordPress has an awesome oEmbed feature where a user just has to enter the url of the media you want embedded and WordPress takes care of the rest. Sadly, this only works when you put the link in the content. If you're creating custom post types, a plugin, or using custom meta data you may run into a situation where you want to embed some media that isn't in the content in which case you need to do a little coding.

Apply Filters to the Media

The first thing we have to do is add a filter right before you print your content. You can think of the apply_filters() function as a placeholder for more code.


<?php
// get media; could be a url to a tweet, or youtube video, or something else;
$media;
$media = apply_filters( "my_media_filter", $media );
// add filter for oEmbed
$media = apply_filters( "my_media_filter", $media );
// print embedded media
echo $media;

view raw

functions.php

hosted with ❤ by GitHub

Add WordPress Embed Functionality to Filter

The last thing we have to do is tell WordPress to add the default oEmbed functionality to anything in our filter.


<?php
// add filters for oEmbed
global $wp_embed;
add_filter( 'my_media_filter', array( $wp_embed, 'autoembed' ), 8 );

view raw

functions.php

hosted with ❤ by GitHub

Conclusion

You're custom post data has the awesome oEmbed functionality. Time to celebrate. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.