如何为WordPress嵌入的YouTube竖版视频添加手机框架
解决WordPress嵌入竖版YouTube视频并自动添加手机框架的方法
方法1:HTML+CSS 直接嵌入(复制即用)
不需要插件,直接在WordPress的自定义HTML块里粘贴代码,替换视频ID就能用,适合快速插入单条视频。
代码示例
<div class="phone-frame-container"> <div class="phone-frame"> <iframe width="360" height="640" src="https://www.youtube.com/embed/你的YouTube视频ID?rel=0&showinfo=0" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> <style> .phone-frame-container { display: flex; justify-content: center; margin: 20px 0; } .phone-frame { width: 360px; height: 640px; background: #000; border-radius: 40px; padding: 60px 15px; box-sizing: border-box; box-shadow: 0 10px 30px rgba(0,0,0,0.3); position: relative; } .phone-frame::before { content: ''; position: absolute; top: 20px; left: 50%; transform: translateX(-50%); width: 60px; height: 10px; background: #333; border-radius: 5px; } .phone-frame iframe { width: 100%; height: 100%; border-radius: 30px; } </style>
使用说明
- 把代码里的
你的YouTube视频ID替换成你未列出视频的ID(比如链接https://www.youtube.com/watch?v=abc123里的abc123) - 调整
width和height数值可以改变框架大小,保持360:640的比例对应9:16竖版视频即可 - 直接粘贴到WordPress的「自定义HTML」区块中,每条视频替换ID重复操作就行
方法2:WordPress短代码(批量更高效)
如果要处理几百条视频,用短代码能避免重复写CSS,操作更快捷。
步骤1:添加短代码到主题functions.php
登录WordPress后台,进入「外观」→「主题文件编辑器」,找到functions.php,在末尾粘贴以下代码:
function phone_frame_youtube_shortcode($atts) { $atts = shortcode_atts(array( 'id' => '', 'width' => '360', 'height' => '640' ), $atts); if (empty($atts['id'])) return ''; $output = '<div class="phone-frame-container" style="display:flex;justify-content:center;margin:20px 0;">'; $output .= '<div class="phone-frame" style="width:'.$atts['width'].'px;height:'.$atts['height'].'px;background:#000;border-radius:40px;padding:60px 15px;box-sizing:border-box;box-shadow:0 10px 30px rgba(0,0,0,0.3);position:relative;">'; $output .= '<div style="position:absolute;top:20px;left:50%;transform:translateX(-50%);width:60px;height:10px;background:#333;border-radius:5px;"></div>'; $output .= '<iframe width="100%" height="100%" src="https://www.youtube.com/embed/'.$atts['id'].'?rel=0&showinfo=0" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="border-radius:30px;"></iframe>'; $output .= '</div></div>'; return $output; } add_shortcode('phone_youtube', 'phone_frame_youtube_shortcode');
步骤2:用短代码嵌入视频
在文章或页面里添加「短代码」区块,输入:
[phone_youtube id="你的YouTube视频ID"]
需要调整框架大小的话,加上宽高参数:
[phone_youtube id="你的YouTube视频ID" width="400" height="711"]
注意事项
- 修改主题文件前记得备份
functions.php,避免出错 - 用子主题的话,建议把代码加到子主题的
functions.php里,防止主题更新时代码丢失
额外优化小技巧
- 隐藏YouTube控件:在嵌入链接里加
controls=0参数,变成https://www.youtube.com/embed/你的ID?rel=0&showinfo=0&controls=0,更贴近原生手机播放效果 - 自动播放:添加
autoplay=1&mute=1(YouTube要求静音才能自动播放),适合沉浸式展示
内容的提问来源于stack exchange,提问作者mylegshurt
相关产品推荐
相关产品推荐

