从wordpress帖子中检索嵌入的YouTube视频

问题描述 投票:0回答:3

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视频并摆脱其余部分?我有两个想法:

  1. 例如,我可以获取前X个字符,找到嵌入的结尾并摆脱其余部分。
  2. 我可以在帖子中添加一个特殊元素并将其中的所有内容都包含在内。就像是: qazxsw poi
  3. 理论上,我只能使用视频本身创建帖子,只需使用the_content(),但我想避免使用此解决方案,因为只是分享视频而对网站用户没有任何附加价值的网站有时会被谷歌在搜索排名中处罚。
  4. 我可以直接从embed div中提取src元素。

哪种方法最好,还是有更好的方法呢?如果是这样,你能指出我正确的方向吗?

谢谢你的任何建议。

php wordpress
3个回答
1
投票

我可以给你完成代码,但是尝试自己做,你将来可能会需要它。

你应该使用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


0
投票

使用第一个答案的资源以及更多的研究我做了这个功能:

http://pastebin.com/FhV5yQTV

0
投票

从版本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>, ]

© www.soinside.com 2019 - 2024. All rights reserved.