【问题标题】:Catch Youtube video in Wordpress post and insert into custom field value在 Wordpress 帖子中捕捉 Youtube 视频并插入自定义字段值
【发布时间】:2014-08-08 14:03:12
【问题描述】:

谁能帮帮我,我需要扫描帖子以获取 youtube 视频。如果帖子包含视频 (www.youtube.com/embed/youtubepostid),那么我想将该 URL 复制到带有键 "iFrame" 的自定义字段中。

我正在兜圈子寻找答案,每当我尝试 soething 时,我都会使用 WSD :(

任何指向正确方向的指针?

【问题讨论】:

  • 这是一个相当广泛的问题。到目前为止,尝试了什么?结果如何?
  • 你需要更多的逻辑。 str_pos 将返回字符串 www.youtube.com 的字符串位置,然后您可以找到下一个空格,然后将其替换掉。但这是一个弱逻辑。网址保存在哪里?你能不能挂钩一个函数或改变它以保存到post_meta等中。

标签: php wordpress video youtube


【解决方案1】:

我编写了一些代码来解决我们的常见问题;) 如果您想要显示格式化的嵌入视频(在帖子内容之外),我也添加了一些内容。

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(); ?>

瞧!享受 ! (对不起我的英语不好)

【讨论】:

    【解决方案2】:

    我尝试实施,但收到一个警告和一个通知。

    1. add_post_meta($post-&gt;ID, 'iFrame', $youtubeUrl);需要一个;关闭。我修复了警告。

    2. "注意:未定义的偏移量:$youtubeUrl = $matches[0][0]; 中的 0,我不知道如何修复它:(

    感谢任何帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多