dqybjj3497 2014-08-08 14:03
浏览 38

在Wordpress帖子中捕获Youtube视频并插入自定义字段值

Could anyone help me out, I need to scan the post for a youtube video. If the post contains a video (www.youtube.com/embed/youtubepostid) then I'd like to copy that url into a custom field with the key "iFrame".

I'm going round in circles looking for an answer and whenever I try soething I get up with the WSD :(

Any pointers in the right direction?

  • 写回答

2条回答 默认 最新

  • dongshiliao7990 2014-11-08 16:01
    关注

    I have coded something to solve our common problem ;) I have added something too if you to display your formatted embed video whatever you want (out of the post content).

    I - Add these functions to your 'functions.php' file

    1- Remove the youtube embed from content

    function remove_video( $content ) {
        $postOutput = preg_replace('/<iframe[^>]+./','', $content);
        return $postOutput;
    }
    add_filter( 'the_content', 'remove_video', 100 );
    

    2 - Catch and return the youtube embed from content

    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 - Call those functions in your post template content

    1 - Show the post's content in your post template without the embed video

    remove_filter(the_content(),'remove_video', 100 );
    

    2 - Show the embed video iframe whatever you want to !

    <?= catch_first_youtube_video(); ?>
    

    And voilà ! Enjoy ! (Sorry for my bad english)

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀