I have a function that gets the first oembed in the post. I got the code from this related post.

add_filter('embed_oembed_html', 'my_function',10,4);
function my_function( $cache, $url, $attr, $post_ID ) {
  global $my_previous_post_id;
  if ($my_previous_post_id != $post_ID) {
    // post ID changed, so this is the first oembed for the post
    // do something with $url
    $my_previous_post_id = $post_ID;
  return $cache; // it's important that you return the $cache value as-is

How can I get the first oembed from a post and make it a global variable? If that is not possible can we make the oembed url as post meta in order to access the first oembed anywhere?

I need to be able to access the first oembed in a loop within my shortcode.

You can get the first image in in a post (featured image) through a function:


You can get the first oembed in a post by:


@Otto wrote how to get the first oembed but how can we access it?

  • What is the global used for?
    – s_ha_dum
    Jun 3, 2015 at 13:35
  • <?php function my_shortcode() { ob_start(); ?> <!-- Anything found here will be returned when called in a shortcode [my-shortcode] --> <?php return ob_get_clean(); } add_shortcode('my-shortcode', 'my_shortcode');
    – Ismail
    Jun 3, 2015 at 13:37
  • I am using ob_start() and ob_get_clean(); with my my custom shortcode to prevent it from hoisting to the top in the wp editor; I know about that already.
    – user73579
    Jun 3, 2015 at 13:39
  • @s-ha-dum I am trying to access the first oembed from a post to use in a for each loop in my shortcode.
    – user73579
    Jun 3, 2015 at 13:44
  • I am still not clear about the global. It isn't that WordPress "doesn't like them" exactly. It is that they are messy and very rarely actually necessary. But nonetheless, you set global $embedCode but you don't use it anywhere. I think you are going about this wrong but I am trying to get at the complete sequence of events, the complete logic. Can you sketch the logic from start to finish in words?
    – s_ha_dum
    Jun 3, 2015 at 14:22

1 Answer 1


Since WordPress 3.6+

There is a function to print out all the media in the content.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.