Getting results from wp_oembed_add_provider

Ok I managed to solve this!

Did some digging through how the embed system works, and it turns out it wasn’t the use of wp_oembed_add_provider() that was wrong. Debugging autoembed_callback() in wp-includes\class-wp-embed.php showed that my YouTube URL was coming through but my Facebook URL never made it to this function.

Echo’ing the post content before it went through the autoembed() function (hooked to the_content()) showed that for some reason, the Facebook URL was ‘not on a new line’ as required by autoembed() and was wrapped in <p></p> tags, and part of another line, even though it was clearly on its own new line in the editor.

I’m not sure why the FB URL didn’t make it to its own line, but taking a cue from how autoembed() works, I’ve added the following to my functions.php:

add_filter("the_content", function($content){

    // Find URLs that are on their own line but are wrapped in <p></p> tags

    return preg_replace_callback(
        '|^\<p\>(\s*)(https?://[^\s"]+)(\s*)\</p\>$|im',
        array($GLOBALS["wp_embed"], "autoembed_callback"),
        $content
    );

}, 11);

As long as this runs after wpautop() (which runs on the_content at default priority 10), both links are correctly moved to a new line, wrapped in <p></p> tags, and this function sends the detected URLs through to the autoembed_callback, at which point everything kicks in as it should.

Whew. So the real problem is something to do with line breaks, and possibly the way WordPress detects URLs to auto embed. I imagine that regex in core could probably be better in order to pick up edge cases, but hopefully this additional function catches that issue for now. I’ll update this if I come across any additional issues that this causes.