2013-05-21 8 views
0

У меня есть CMS, и администратор может ссылаться, чтобы показать видео, которое я ввожу в заголовок, а затем код вставки, который сохраняется в базе данных.Как показать миниатюры youtube на моем сайте вместо встроенного видео

Когда сайт показывает список видеороликов, он показывает все видео в своей внедряемой форме. Есть ли способ сделать эти встроенные видео-скрипты стать миниатюрами, которые будут использовать меньшую пропускную способность.

+0

так, спасибо :) –

ответ

1

Вот функция, которую я написал, чтобы захватить различные фрагменты информации YouTube для WordPress CMS, которая является PHP.

Чтобы использовать его, вы должны извлечь видеокод с URL-адреса. Я также включаю в себя те функции, которые я использовал для этого.

Обратите внимание, что вы не упомянули о CMS, которую используете. Я прокомментировал в своем коде, где я получаю URL-адрес изначально; поскольку я использую WordPress и дополнительные пользовательские поля, я захватываю URL-адрес из подполя ACF. Вы можете передать его, как вам нужно. :)

// Grab the video's url from your CMS. 
// get_sub_field() is an Advanced Custom Fields function from WordPress 
// Make sure to swap it out with however you plan on passing this in 
// The URL can be formed as http://www.youtube.com/watch?v=9bZkp7q19f0 
// Note that I didn't include functionality for http://youtu.be type of urls, 
// but you could work that out. :) In my web app, I also have a similar Vimeo function, 
// which is why I even bother to check the url in the first place. 
$video_url = get_sub_field('CMS_video_url'); 
$video_url_a = parse_url($video_url); 

// Check if this is a youtube video. You could add in youtu.be logic here. 
if($video_url_a['host'] == 'www.youtube.com' || $video_url_a['host'] == 'youtube.com'){ 
     $array = explode("&", $video_url_a['query']); 
     $video_id = substr($array[0],2); 

     // Grab the info for a large thumbnail. You could also grab a small thumb, 
     // as well as the title, the description, the author, or the author's uri. 
     // See the get_youtube_info() function below 
     $videothumb = get_youtube_info($video_id, 'thumbnail_large'); 

     // So here's an example of grabbing the video title for the alt tag. :) 
     $videotitle = get_youtube_info($video_id, 'title'); 
} else { 
     // enter whatever fail functionality you want 
} 

echo '<img class="video-thumb" src="' . $videothumb . '" alt="' . $videotitle . '" />' 

А вот функция get_youtube_info():

/* 
    * Here's a function to get a limited set of youtube info 
    * see switch in function 
    * an example JSON returned: Gungnam Style! 
    * http://gdata.youtube.com/feeds/api/videos/9bZkp7q19f0?v=2&alt=json-in-script&prettyprint=true 
*/ 
function get_youtube_info ($vid, $info) { 
    $youtube = "http://gdata.youtube.com/feeds/api/videos/$vid?v=2&alt=json&feature=related"; 
    $ch = curl_init($youtube); 
    curl_setopt($ch, CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $output = curl_exec($ch); 
    curl_close($ch); 

    //If $assoc = true doesn't work, try: 
    //$output = json_decode($output, true); 
    $output = json_decode($output, $assoc = true); 

    //Add the ['feed'] in if it exists. 
    if ($output['feed']) { 
     $path = &$output['feed']['entry']; 
    } else { 
     $path = &$output['entry']; 
    } 

    //set up a switch to return various data bits to return. 
    switch($info) { 
     case 'title': 
      $output = $path['title']['$t']; 
      break; 
     case 'description': 
      $output = $path['media$group']['media$description']['$t']; 
      break; 
     case 'author': 
      $output = $path['author'][0]['name']; 
      break; 
     case 'author_uri': 
      $output = $path['author'][0]['uri']; 
      break; 
     case 'thumbnail_small': 
      $output = $path['media$group']['media$thumbnail'][0]['url']; 
      break; 
     case 'thumbnail_medium': 
      $output = $path['media$group']['media$thumbnail'][2]['url']; 
      break; 
     case 'thumbnail_large': 
      $output = $path['media$group']['media$thumbnail'][3]['url']; 
      break; 
     default: 
      return $output; 
      break; 
    } 
    return $output; 
} 
Смежные вопросы