3 Answers
3

I assume that you're only interested in the first URL that actually succeeds at discovering actual oembed data. The oembed system processes all links it finds, but not every link will have oembed going for it, obviously.

The filter you'll want to use is embed_oembed_html and it gets the HTML cached by oembed, the url, any attributes on the embed, and the post_ID, which is important for your code.

Now, the whole oembed system is running at the same time as shortcodes do: during the_content filter call. So if you want to grab stuff for the header, you'll have to start the main Loop in the header, run the_content filter over the get_the_content() value, then call rewind_posts() to rewind the query back to the start for the actual main Loop later on in the page.

This sort of behavior causes problems with plugins (like Nextgen gallery) that do stupid things when you run a loop in the header. There's no working around it, but the fact is that those plugins are fundamentally broken and you can't correct their problems. I get this sort of report with SFC-Share and SFC-Like all the time (because they pull content out to put in the header too). Nothing you can do about it, frankly.

I have tried the answer from the @Rarst, but in fact it is not very stable solution to the problem. If you try to var_dump the $meta var above, you will notice that there is at least one another meta field _oembed_time_xxxxxxxxxxxx which is probably for cache busting.

And also, when I removed the oEmbed link from the content of the post, the cached eEmbed meta strings were not removed, which is not what I wanted.

So I dig a bit deeper in the native WP codes of the wp-includes/class-oembed.php and wp-includes/class-wp-embed.php and came up with much more solid solution:

This function only works if the first url is the oembed. I've included an updated function that will return the first oembed, no matter where it is in the content. function get_first_oembed_from_content( $content ) { preg_match_all( '|^\s*(https?://[^\s"]+)\s*$|im', $content, $matches ); foreach ($matches[1] as $match) { if (wp_oembed_get($match)) { return $match; } } return false; }
–
Chad von NauFeb 20 at 2:46