I’m building a portfolio plugin for a Video Director. The client wants to simply add a YouTube URL to a ‘New Project’ with a ‘Portfolio’ Custom Post Type in WordPress.

I wanted it to automatically extract the thumbnail image associated with that YouTube video directly from YouTube.

The Solution

  1. Query your post type meta.
  2. Extract the YouTube ID
  3. Pass it to $id
  4. Echo the ID (and a width and height variable) to an img src
  5. Voila!

query_posts( array( 'posts_per_page' => 3, 'post_type' => 'project','orderby' => 'ASC',) );
if ( have_posts() ) : while ( have_posts() ) : the_post();
//retrieve the URL from the project post meta
global $wp_query;
$postid = $wp_query->post->ID;
$url = get_post_meta( $postid, '_wpb_video_embed', true );
//extract the youtube ID
//pass the youtube ID to $id
$id = $matches[1];
//set a custom width and height
$width = '365';
$height = '220';
//echo the embed code.
echo '< img class="responsive" src="//'.$id.'/0.jpg" alt="" width="' .$width. '" height="'.$height.'" />';