I have PHP script outside the WordPress directory where I'm getting the content of a specific post and now trying to apply the oembed filter on it:

$thePost = get_post(42, ARRAY_A);
$theContent = $thePost['post_content'];

The post's content contains text and one or more URLs to YouTube (or similar pages). Obviously WordPress is able to discover those URLs and rewrite them to embeds, but I have no idea how to apply this behavior on my code snippet.

I know there's wp_oembed_get, but that function doesn't do the auto-discovery.

Any idea how to achieve this?

2 Answers 2


You need to set the global $post object to your post. This is done by the loop functions in your theme which is why it works there.

WP's oEmbed replaces the URLs during the the_content filter. But it replaces the URLs through two means. The first is a simple regex find and replace for certain URLs such as Google Video or linking directly to a file with a video format extension.

The second way oEmbed handles it is the way most services (such as YouTube) are handled. The second way is similar to the first except that the results are stored in the postmeta table which is why we need to set the $post. In the second way, the various services handlers are asked if a URL is theirs. If the URL is theirs, they will generate the HTML for the embed. Then oEmbed caches the HTML for the URL into the postmeta table. The reason for this is because a services may require a remote API call to get the HTML code, and we would like to minimize this overhead each time the post is displayed.

$thePost = get_post(42);

// Set our post to the globally used $post object as oEmbed will use it to do a meta value lookup
global $post; 
$post = $thePost;

echo apply_filters('the_content', $thePost->post_content );

"autoembedding", at least last I checked, operates due to a filter on the_content. Your code does not apply that filter.

$thePost = get_post(42, ARRAY_A);
$theContent = $thePost['post_content'];
echo apply_filters('the_content',$theContent);

Assuming that the WordPress Core is loading correctly, that should get the embeds working.

  • Thanks, but unfortunately this doesn't work: (YouTube) URLs in $theContent still don't get replaced.
    – Patrick
    Commented Mar 1, 2014 at 17:27
  • Interesting. I tried that with a YouTube URL
    – s_ha_dum
    Commented Mar 1, 2014 at 18:03
  • I just tested this on a second dev stack and apply_filters('the_content'is the trick. If this is not working for you there is something happening that I can't duplicate. My guess is that the include('../wp-load.php'); hack is breaking thing.
    – s_ha_dum
    Commented Mar 1, 2014 at 21:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.