Import YouTube & Vimeo Video Covers Into WordPress Media Library


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Import YouTube & Vimeo Video Covers Into WordPress Media Library

We had a client that was re-designing their site and it incorporated a lot of video. The previous design of the site used video embed codes but the new design was set to show video in a lightbox popup. Due to this change in functionality, there had to be a clickable image that pulled up the video lightbox.

Trying to go through thousands of programs within this website and adding a video cover would have taken forever. Therefore, we wrote a plugin that fetched the Vimeo or YouTube video cover image, uploaded it to the WordPress media library, and then set it as a video cover to our defined Advanced Custom Fields field.

We used two different guides that were previously shared on WP Cover as a base for developing this functionality. The first was our ‘Do Random Things‘ plugin which is just a framework for creating plugins quickly. The second was our plugin for Importing Images from Flickr into WordPress.

I’ll explain the code quickly and then provide the full plugin below. Here’s what we’re doing:

  • Grabbing the video link and determining if it is a YouTube or Vimeo video.
  • Based on that information, we’re grabbing the static image file for the video.  The method for doing this is different based on whether the video is from YouTube or Vimeo.  In this case, we’re grabbing the highest resolution image file but there are other options.
  • If we’re successful in grabbing the URL, we’re going to save it to our wp-uploads folder and add it to the media library using wp_insert_attachment.
  • Finally, we’re going to assign it to the necessary Advanced Custom Fields field already setup.

Here is the full source of the plugin.  Enjoy!

 

<?php
/**
* Plugin Name: Import & Set Video Covers
* Plugin URI: https://www.wpcover.com
* Description: Custom plugin to import youtube and vimeo covers into wordpress
* Version: 1.0
* Author: Cabe Nolan
* Author URI: https://www.boldcitydesign.com
* License: GPL12
*/
 
/*---------------------------------------------------
add settings page to menu
----------------------------------------------------*/
function add_flickr_import_page() {
add_submenu_page( 'tools.php', 'Import Video Covers', 'Import Video Covers', 'manage_options', 'import-flickr', 'import_flickr' );
}
add_action( 'admin_menu', 'add_flickr_import_page' );
 
function import_flickr() {
?>
 
<div class="wrap import-csv">
    <h2>Import Video Covers</h2>
    <p>Click Process button to run through posts and import data.</p>
    
<?php
//some security checks
    if ( isset( $_POST['_wpnonce-is-iu-import-users-users-page_import_cn'] ) ) {
    check_admin_referer( 'is-iu-import-users-users-page_import_cn', '_wpnonce-is-iu-import-users-users-page_import_cn' );
    // setup our query args
    $args = array(
        'posts_per_page'    => -1,
        'post_type'     => 'programs',
    );
     
    $the_query = new WP_Query( $args );
    if( $the_query->have_posts() ):
        while( $the_query->have_posts() ) : $the_query->the_post();
        $parent_post_id = get_the_ID();
        if(get_field('video_embed') && !get_field('video_cover')) { $i++;
            $vidembed = get_field('video_embed');
            $coversrc= '';
            if (strpos($vidembed, 'youtube') > 0) {
	         	$type = 'youtube';
	         	$explode = explode('v=', $vidembed);
	         	$youtubekey = $explode[1];
	         	$coversrc = 'https://img.youtube.com/vi/' . $youtubekey . '/maxresdefault.jpg';   
	        } else {
		        $type = 'vimeo';
		        $explode = explode('vimeo.com/', $vidembed);
		        $imgid = $explode[1];
				$hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$imgid.php"));
				$coversrc = $hash[0]['thumbnail_large'];  
	        }
			
    		if(!empty($coversrc)) {
                     
                $filename = rand(10000, 999999999) . '.jpg';
                $uploaddir = wp_upload_dir();
                $uploadfile = $uploaddir['path'] . '/' . $filename;
                $contents= file_get_contents($coversrc);
                if(empty($contents)) { $failedgal[] = $parent_post_id; }
                $savefile = fopen($uploadfile, 'w');
                fwrite($savefile, $contents);
                fclose($savefile);
                 
                $wp_filetype = wp_check_filetype(basename($filename), null );

                $attachment = array(
                    'guid'           => $wp_upload_dir['url'] . '/' . $filename, 
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title' => $filename,
                    'post_content' => '',
                    'post_status' => 'inherit'
                );
                 
                $attach_id = wp_insert_attachment( $attachment, $uploadfile, $parent_post_id );
                 
                // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
                require_once( ABSPATH . 'wp-admin/includes/image.php' );
                 
                // Generate the metadata for the attachment, and update the database record.
                $attach_data = wp_generate_attachment_metadata( $attach_id, $uploadfile );
                wp_update_attachment_metadata( $attach_id, $attach_data );
                 
                update_field('video_cover', $attach_id);
            }
							
        }
        endwhile; 
    endif; wp_reset_query();
    }
?>

    <form method="post" action="">
        <?php wp_nonce_field( 'is-iu-import-users-users-page_import_cn', '_wpnonce-is-iu-import-users-users-page_import_cn' ); ?>
        <p class="submit">
            <input type="submit" class="button-primary" value="Process Posts" />
        </p>
    </form>
<?php } ?>


Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!