Use Auto Embed with get_post()

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:

include('../wp-load.php');
$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.

Read More

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

Any idea how to achieve this?

Related posts

2 comments

  1. 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.

    include('../wp-load.php');
    $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 );
    
  2. “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.

Comments are closed.