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?


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 [embed] 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.

|improve this answer|||||
  • yes I thought too it would be more involved, before digging through similar stuff here ;-) – birgire Sep 15 '15 at 0:14
  • I think it is better to use $wp_embed->autoembed( $post->post_content );, isn't it @kaiser? – cybmeta Sep 15 '15 at 8:57
  • 1
    @cybmeta Actually you need both. They have a different purpose (plain links and [embed] shortcode). – kaiser Sep 15 '15 at 12:10
  • I forgot about [embed], I never use it. – cybmeta Sep 15 '15 at 12:38
  • @birgire Updated with a link to your answer. – kaiser Nov 4 '15 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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