我编写了一些代码来解决我们的常见问题;)
如果您想要显示格式化的嵌入视频(在帖子内容之外),我也添加了一些内容。
I - 将这些函数添加到您的“functions.php”文件中
1- 从内容中删除 youtube 嵌入
function remove_video( $content ) {
$postOutput = preg_replace('/<iframe[^>]+./','', $content);
return $postOutput;
}
add_filter( 'the_content', 'remove_video', 100 );
2 - 从内容中捕获并返回 youtube 嵌入
function catch_first_youtube_video() {
global $post, $posts;
// Catch youtube iframe src
preg_match_all('/(http|https).*(yout).*/i', $post->post_content, $matches);
$youtubeUrl = $matches[0][0];
// Set the new meta for your post.
add_post_meta($post->ID, 'iFrame', $youtubeUrl)
// Remove http: or https:
$formated = preg_replace('/(http:|https:|watch\\?v=)/i','', $youtubeUrl);
// Formated string '//youtube.com/embed/XXXXXXX'
$formated =str_replace('youtube.com/','youtube.com/embed/', $formated );
return '<iframe src="'.$formated .'"></iframe>';
}
II - 在您的帖子模板内容中调用这些函数
1 - 在没有嵌入视频的帖子模板中显示帖子内容
remove_filter(the_content(),'remove_video', 100 );
2 - 随心所欲地显示嵌入视频 iframe!
<?= catch_first_youtube_video(); ?>
瞧!享受 ! (对不起我的英语不好)