Wordpress:如何将youtube视频网址转换为iframe嵌入代码

时间:2014-12-23 12:30:46

标签: wordpress

我有一个WYSIWYG textarea,有时用户可以在框中输入youtube url。在服务器端,有html过滤器,以防止"有害"代码来自被保存。

相反,我希望保持服务器代码不变,并运行jQuery文档就绪事件,搜索youtube链接的文本块,并将其转换为iframe嵌入代码。< / p>

我想象它会以正则表达式为基础,但我对正则表达式非常可怕(在某些时候,我真的需要坐下来研究它们。)

两种类型的YouTube链接:

http://www.youtube.com/watch?v=t-ZRX8984sc

http://youtu.be/t-ZRX8984sc

1 个答案:

答案 0 :(得分:0)

将整个代码块放入主题目录下的functions.php

function replaceYouTube($string) {
    $pattern = '@(http|https)://(www\.)?youtu[^\s]*@i';
    //This was just for test
    //$string = "abc def http://www.youtube.com/watch?v=t-ZRX8984sc ghi jkm";
    $matches = array();
    preg_match_all($pattern, $string, $matches);
    foreach ($matches[0] as $match) {
        $string = str_replace($match, '<iframe width="560" height="315" src="' . $match . '" frameborder="0" allowfullscreen></iframe>', $string);
    }
    return $string;
}
add_filter( 'the_content', 'replaceYouTube' );