tl; dr:我想从特定类别的帖子中提取嵌入式Youtube视频链接
我目前正在开发一个博客/文章网站。请考虑以下内容:我有一个索引页面,其中包含2个精选视频的部分。假设我有一个查询和一个从一个类别中检索2个最新帖子的循环。此类别中的帖子始终以使用引导程序嵌入的精选视频开头:
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>
<!-- some text content follows -->
目前我正在使用以下函数从帖子内容中检索文本摘录:
function get_excerpt_by_id($post_id){
$the_post = get_post($post_id); //Gets post ID
$the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
$excerpt_length = 30; //Sets excerpt length by word count
$the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
$the_excerpt = html_entity_decode($the_excerpt, ENT_QUOTES, 'UTF-8');
$words = explode(' ', $the_excerpt, $excerpt_length + 1);
if(count($words) > $excerpt_length) :
array_pop($words);
array_push($words, '…');
$the_excerpt = implode(' ', $words);
endif;
return $the_excerpt;
}
该函数从帖子中获取内容并提取前30个单词,同时去除所有html标签和图像。我怎么能这样做呢?以某种方式检索嵌入的YouTube视频并摆脱其余部分?我有两个想法:
哪种方法最好,还是有更好的方法呢?如果是这样,你能指出我正确的方向吗?
谢谢你的任何建议。
我可以给你完成代码,但是尝试自己做,你将来可能会需要它。
你应该使用DOM,你可以用正则表达式提取视频ID。例如:
<span class="vid">...</span>
ID是https://www.youtube.com/watch?v=EuQLMXyGQOE
EuQLMXyGQOE
http://php.net/manual/en/book.dom.php
编辑:如果你被困,这里是完成代码http://php.net/manual/en/function.preg-match.php
使用第一个答案的资源以及更多的研究我做了这个功能:
http://pastebin.com/FhV5yQTV
从版本3.6.0开始,WordPress引入了 <?php
$args = array(
'category_name' => 'featured-video',
'posts_per_page' => '2'
);
query_posts($args);
if (have_posts()) : while (have_posts()) : the_post();
$content = $post->post_content;
$doc = new DOMDocument();
@$doc->loadHTML($content);
$iframes = $doc->getElementsByTagName('iframe');
foreach ($iframes as $frame) {
echo '<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="'.$frame->getAttribute('src').'" frameborder="0" allowfullscreen></iframe>
</div><br>';
}
endwhile; endif;
wp_reset_query();
?>
函数来轻松嵌入内容。
get_media_embedded_in_content()
支持的音频类型:“音频”,“视频”,“对象”,“嵌入”或“iframe”。
您可以在这里找到更多信息$media = get_media_embedded_in_content(
apply_filters( 'the_content', get_the_content() ), 'video'
);
print_r($media);
// results
[
0 => '<iframe>content</iframe>,
]
。