Extracting Thumbnails from Videos

Recently, I’ve had a couple of projects that require thumbnails for video posts. There are plugins out there to do this, but I wanted a simple, lightweight way. Good news is, this can be achieved very easily by making use of WordPress’s WP_Embed class.

/**
 * Maybe get thumbnail from embed
 *
 * @param string $string
 * @return bool
 */
function get_embed_thumbnail_from_string_maybe ($string) {

    $found = preg_match_all('|^\s*(https?://[^\s"]+)\s*$|im', $string, $matches);
    if (!$found) return false;

    // nb: this can be used if we're just checking an embed exists and is supported
    //foreach ($matches[1] as $match) if (wp_oembed_get($match)) return $match;

    $embed = new WP_oEmbed();
    foreach ($matches[1] as $match) {
        if ($embed->get_html($match)) {
            return $embed->get_data($match)->thumbnail_url;
        }
    }
    return false;
}

Place the code above in a custom functionality class or, for a crude option, dump it in the functions.php file and call it when a thumbnail of the first video in a string is required. An obvious use case is the blog archive page when displaying thumbnails with each post link.

We develop custom WordPress solutions. If you have any advanced WordPress requirements, including custom themes, plugins or theme modifications, please let us know.