2014-03-26 22 views
0

我使用下面的代碼輸出的最新視頻的視頻嵌入:在HTML集成此正則表達式的代碼到現有的PHP代碼

$args = array( 
    'numberposts' => '1', 
    'tax_query' => array(
     array(
      'taxonomy' => 'post_format', 
      'field' => 'slug', 
      'terms' => 'post-format-video' 
     ) 
    ), 
    'meta_query' => array(
     array(
      'key' => 'dt_video', 
      'value' => '', 
      'compare' => '!=' 
     ) 
    ) 
); 
$latest_video = wp_get_recent_posts($args); // Get latest video in 'video' post format 
$latest_video_id = $latest_video['0']['ID']; // Get latest video ID 
$video_url = htmlspecialchars(get_post_meta($latest_video_id, 'dt_video', true)); 
echo '<iframe width="180" height="101" src="'.$video_url.'?rel=0&output=embed" frameborder="0" allowfullscreen></iframe>'; 

的URL輸出正常,但視頻不顯示我得到以下錯誤在控制檯:

Refused to display 'http://www.youtube.com/watch?v=l4X2hQC32NA&feature=g-all-u&context=G258729eFAAAAAAAAHAA?rel=0' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

經過一番搜索,我發現,這是因爲視頻的格式不正確。

在上述錯誤的格式應該是這樣的網址:www.youtube.com/embed/l4X2hQC32NA?rel=0

所以,我found a way動態地改變與下面的代碼的格式爲:

$text = $post->text; 
    $search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*<\/a>#x'; 
    $replace = '<iframe width="180" height="101" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe>'; 
    $text = preg_replace($search, $replace, $text); 
echo $text; 

但是,我不知道我是怎麼可以將其實現爲原始代碼,以便我可以更改輸出URL的格式。有人可以告訴我怎樣才能做到這一點?

回答

1

像這樣:

$video_url = "http://www.youtube.com/watch?v=l4X2hQC32NA&feature=g-all-u&context=G258729eFAAAAAAAAHAA?rel=0"; 
$search = '#(?:href="https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch?.*?v=))([\w\-]{10,12}).*$#x'; 
$replace = "http://www.youtube.com/embed/$1"; 
preg_match_all($search, $video_url, $matches); 
$embedded_video_url = preg_replace($search, $replace, $video_url) ; 
echo '<iframe width="180" height="101" src="'.$embedded_video_url.'" frameborder="0" allowfullscreen></iframe>'; 

您只需使用自己的$video_url

+0

謝謝。我不得不在第三行中刪除'http://',因爲它是這樣不必要地添加的:'http:// http // www.youtube.com/embed/l4X2hQC32NA'但現在它正在工作。 – J82