How to use oEmbeds on Post Content during AJAX requests

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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 stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x