How to use oEmbeds on Post Content during AJAX requests

The question:

I have an AJAX request that returns a post. The post_content has links to Twitter, YouTube, TED and other platforms that are registered as oEmbed providers in a default, vanilla WordPress install. By now, the WordPress oEmbed handler does not register them and displays plain links and nothing else.

How can I fetch content via AJAX with oEmbed support?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Actually this was quite easy – when you know what’s missing: The current post ID for the global $wp_embed object, so it knows what to refer to. The reason is simple: oEmbeds get cached as post meta data, so without knowing the ID, the MarkUp can’t get fetched and replaced in the content.

// grab a post from the database

/** @var WP_Embed $wp_embed */
global $wp_embed;

/** @var WP_Post $post; */
// Add the fetched posts ID and add it to the global object
$wp_embed->post_ID = $post->ID;

// Execute the  shortcode
$wp_embed->run_shortcode( $post->post_content );

// Execute the oEmbed handlers for plain links on the own line
$wp_embed->autoembed( $post->post_content );

That’s it.

More in depth info about oEmbed and caching can be found in a related answer by @birgire.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment