Embedding videos in WordPress is really very simple. Just paste the Video URL into the visual editor and boom! Magic happens!
But there is one minor issue. These videos are not responsive by default and will scale incorrectly like this.
YouTube left and Vimeo right with scaling issues.
There are a number of ways you could fix this, you could go into text editor mode and wrap the video in a div and style accordingly. But we can’t really expect users to do that so another way is to automate that wrapping and styling process.
(function() { var fluid_vids = { fluid_videos: function () { var iframes = document.getElementsByTagName('iframe'); for (var i = 0; i < iframes.length; i++) { var iframe = iframes[i], players = /www.youtube.com|player.vimeo.com/; if (iframe.src.search(players) > 0) { var videoRatio = (iframe.height / iframe.width) * 100; iframe.style.position = 'absolute'; iframe.style.top = '0'; iframe.style.left = '0'; iframe.width = '100%'; iframe.height = '100%'; var wrap = document.createElement('div'); wrap.className = 'fluid-vids'; wrap.style.width = '100%'; wrap.style.position = 'relative'; wrap.style.paddingTop = videoRatio + '%'; var iframeParent = iframe.parentNode; iframeParent.insertBefore(wrap, iframe); wrap.appendChild(iframe); } } } }; fluid_vids.fluid_videos(); })();
Just copy the above code into a file called responsive-video.js
file and upload it to your server and then enqueue it as normal. You can enqueue this in the footer and it can also be loaded asynchronously. Winning!
How to enqueue a JavaScript file in WordPress
function responsive_video_js() { wp_enqueue_script( 'responsive-videos', '/enter/the/path/to/the.js', '', '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'responsive_video_js' );
Copy the above to your functions.php files and change /enter/the/path/to/the.js
to the correct path you uploaded your responsive-video.js file.
Below you can see both a YouTube and Vimeo video embedded in the standard way and both now scale correctly.
YouTube
Vimeo