Detecting Embed URLs Within post_content

OK, got it. I just dug around in wp core a bit and found the function they use to grab autodetcts. WP uses the php preg_replace_callback function within the WP autoembed function. Here is the code, as seen in wp-includes/class-wp-embed.php:

/**
     * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding.
     *
     * @uses WP_Embed::autoembed_callback()
     *
     * @param string $content The content to be searched.
     * @return string Potentially modified $content.
     */
    function autoembed( $content ) {
        return preg_replace_callback( '|^\s*(https?://[^\s"]+)\s*$|im', array( $this, 'autoembed_callback' ), $content );
    }

Since i’m only planning on the client inputting one video per post I use the preg_match function along with this same RegEx patter to achieve what I want:

function embed_url_lookup() {
    if (!have_posts()) return false;

    the_post(); // necessary to use get_the_content()

    $reg = preg_match('|^\s*(https?://[^\s"]+)\s*$|im', get_the_content(), $matches);

    if (!$reg) return false;

    return trim($matches[0]);

} // end embed_url_looku

This will find the first autoembed url and return it.

Leave a Comment