2016-12-08 85 views
1

我想要一个WordPress的功能,它将从链接中获取一个YouTube ID,并自动将其转换为iframe嵌入代码在自定义字段video_url内。YouTube链接到Iframe?

video_url = https://www.youtube.com/watch?v=UqV4uGLQ2L0 

有时OEmbed不能在我的WordPress网站上工作,所以我正在寻找这个解决方案。

此:

https://www.youtube.com/watch?v=UqV4uGLQ2L0 

应自动包装是这样的:以下功能

<iframe width="560" height="315" src="https://www.youtube.com/embed/UqV4uGLQ2L0" frameborder="0" allowfullscreen></iframe> 
+0

,你想在同一个窗口中打开视频吗? –

+0

不打开任何地方,我只需要变成自定义字段值video_url的PHP代码,其中链接到single.php内的完整iframe与函数,所以我实际上并没有改变single.php值。 –

+0

可以请你举个例子。 –

回答

0

使用,它会返回YouTube的嵌入链接。

将你的YouTube网址传入函数,然后它会返回嵌入代码链接。

中的functions.php

function parseVideos($videoString = null) 
{ 
    if (strpos($videoString, 'youtube.com/embed') !== FALSE) 
    { 
     return $videoString; 
    } 
    if (strpos($videoString, 'iframe') !== FALSE) 
    { 
     // retrieve the video url 
     $anchorRegex = '/src="(.*)?"/isU'; 
     $results = array(); 
     if (preg_match($anchorRegex, $video, $results)) 
     { 
      $link = trim($results[1]); 
     } 
    } 
    else 
    { 
     // we already have a url 
     $link = $videoString; 
    }  

    if (strpos($link, 'youtube.com') !== FALSE) { 

     preg_match(
     '/[\\?\\&]v=([^\\?\\&]+)/', 
     $link, 
     $matches 
     ); 
     //the ID of the YouTube URL: x6qe_kVaBpg 
     $id = $matches[1]; 
     return '//www.youtube.com/embed/'.$id; 
    } 
    else if (strpos($link, 'youtu.be') !== FALSE) { 
     preg_match(
     '/youtu.be\/([a-zA-Z0-9_]+)\??/i', 
     $link, 
     $matches 
     ); 
     $id = $matches[1]; 
     return '//www.youtube.com/embed/'.$id; 
    } 
    else if (strpos($link, 'player.vimeo.com') !== FALSE) { 
     // works on: 
     // http://player.vimeo.com/video/37985580?title=0&amp;byline=0&amp;portrait=0 
     $videoIdRegex = '/player.vimeo.com\/video\/([0-9]+)\??/i'; 
     preg_match($videoIdRegex, $link, $matches); 
     $id = $matches[1]; 
     return '//player.vimeo.com/video/'.$id; 
    } 
    else if (strpos($link, 'vimeo.com') !== FALSE) { 
     //extract the ID 
     preg_match(
       '/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/', 
       $link, 
       $matches 
      ); 

     //the ID of the Vimeo URL: 71673549 
     $id = $matches[2]; 
     return '//player.vimeo.com/video/'.$id; 
    } 
    return $videoString; 
    // return data 

} 
+0

它不起作用。是否可能导致我的视​​频链接位于自定义字段video_url内? –

+0

是的,这可能是问题的原因。 @ElmaElma – vrajesh

0

步骤1:检索custom_field称为视频URL的值:

$unescpaed_url = get_post_meta($post->ID, 'video_url', true); 

步骤2:检索之后逃逸url值:

if ($unescpaed_url) { 
    // Returns an empty string for invalid URLs 
    $url = esc_url('http://' . $unescpaed_url); 

    if ('' !== $url) { 
     $display = esc_html($unescpaed_url); 

     print "<a href='$url' target='_blank'>$display</a>"; 
    } 
}