让 WordPress 支持用 iframe 引用优酷和土豆视频

WordPress 中文版内置了「使用 WordPress 的 Embed 功能快速插入优酷视频」的功能,但是代码是用 embed 实现的,也就是说,只引用了一个 .swf 文件,这样不方便移动客户端以及高端主流浏览器的使用。

如今 HTML5 技术流行,国外的视频分享网站鼻祖 YouTube 早已使用 iframe 方式来站外引用视频,并支持 HTML5 + Flash ,基本兼容所有的客户端和浏览器。在国内最大的两只视频网站优酷和土豆也已经有类似的方法。

后台」→「外观」→「编辑」→ 「functions.php」文件,把下面的代码添加进去:

// add youku using iframe
function wp_iframe_handler_youku( $matches, $attr, $url, $rawattr ) {
    // If the user supplied a fixed width AND height, use it
    if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
        $width  = (int) $rawattr['width'];
        $height = (int) $rawattr['height'];
    } else {
        list( $width, $height ) = wp_expand_dimensions( 480, 400, $attr['width'], $attr['height'] );
    }
    $iframe = '<iframe width='. esc_attr($width) .' height='. esc_attr($height) .' src="http://player.youku.com/embed/'. esc_attr($matches[1]) .'" frameborder=0 allowfullscreen></iframe>';
    return apply_filters( 'iframe_youku', $iframe, $matches, $attr, $url, $ramattr );
}
wp_embed_register_handler( 'youku_iframe', '#http://v.youku.com/v_show/id_(.*?).html#i', 'wp_iframe_handler_youku' );
// add tudou using iframe
function wp_iframe_handler_tudou( $matches, $attr, $url, $rawattr ) {
    // If the user supplied a fixed width AND height, use it
    if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
        $width  = (int) $rawattr['width'];
        $height = (int) $rawattr['height'];
    } else {
        list( $width, $height ) = wp_expand_dimensions( 480, 400, $attr['width'], $attr['height'] );
    }
    $iframe = '<iframe width='. esc_attr($width) .' height='. esc_attr($height) .' src="http://www.tudou.com/programs/view/html5embed.action?code='. esc_attr($matches[1]) .'" frameborder=0 allowfullscreen></iframe>';
    return apply_filters( 'iframe_tudou', $iframe, $matches, $attr, $url, $ramattr );
}
wp_embed_register_handler( 'tudou_iframe', '#http://www.tudou.com/programs/view/(.*?)/#i', 'wp_iframe_handler_tudou' );
wp_embed_unregister_handler('youku');
wp_embed_unregister_handler('tudou');

二、使用方法

发文章的时候直接发视频链接即可。

# 更多WordPress技巧,请关注「WordPress专题

方法来源:ttt.tt