我已经开始编码wordpress主题,就像旧的内容有一个短代码一样;
[youtube]http://www.youtube.com/watch?v=4MhsnuHvZoI[/youtube]
但是,此代码使用插件生成自动嵌入区域。事实上,我不想在我的新项目中使用任何插件。出于这个原因,我创建了一个简单的shourtcode;
<?php
// YoutubeEmbed
function youtubekod($atts,$content = null ) {
return '<iframe width="100%" height="315" src="http://www.youtube.com/embed/'.$content.'?rel=0" frameborder="0" allowfullscreen></iframe>';
}
add_shortcode('youtube', 'youtubekod');
?>
但是,如果您检查短代码返回行;你会看到我试图做什么。然而,问题是我如何在[youtube]标签之间获得仅视频id?有你的帮助我会很高兴的。
谢谢。
尝试这个
function youtubekod($atts, $content="") {
parse_str( parse_url( $content, PHP_URL_QUERY ), $youtube_id );
return '<iframe width="100%" height="315" src="http://www.youtube.com/embed/'.$youtube_id[v].'?rel=0" frameborder="0" allowfullscreen></iframe>';
}
add_shortcode('youtube', 'youtubekod');
试试这个。
<?php
// YoutubeEmbed
function youtubekod($atts,$content = null ) {
$url = get_the_content($post->post_content);
$id=0;
preg_match('%(?:youtube(?:-nocookie)?'.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu'.be/)([^"&?/ ]{11})%i', $url, $matches);
if(isset($matches[1])) $id = $matches[1];
if(!$id) {
$matches = explode('/', $url);
$id = $matches[count($matches)-1];
}
$code = '<iframe width="100%" height="315" src="http://www.youtube.com/embed/{id}?rel=0" frameborder="0" allowfullscreen></iframe>';
$code = str_replace('{id}', $id, $code);
return $code;
}
add_shortcode('youtube', 'youtubekod');
?>