Detecting Embed URLs Within post_content

I need to change the way WP outputs html when given an embed URL within the content. Example content within the WP editor:

This is standard content and will be wrapped in a 'p' tag. But check out this cool vid:

http://www.youtube.com/watch?v=3JJv4TvURj4

This will be output as another 'p' tag. The above URL will be turned into an iFrame.

The goal is for the client to input something simple like that, and change the way wordpress outputs it on the page. I have been using the oembed_dataparse filter to good effect so far, but I would like to take the video URL and pass it to another function outside of the filter. How can I do that?

Read More

My initial approach was to use a global variable. Here’s my abridged filter code:

add_filter('oembed_dataparse', 'modal_embed', 10, 3);
function modal_embed($html, $data, $url) {
    // This is supposed to store the URL globally so I can access it 
    // outside this filter.
    global $video_url;
    $video_url = $url;

    $custom_output = "<div class='video'>$html</div>"; // Just an example. 
    return $custom_output;
}

The code I create as $custom_output works just fine and is displayed on the page. The issue is that I’m not getting access to $video_url globally as I expected. Any thoughts? Thanks.

Related posts

1 comment

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

Comments are closed.