Updated August 2015: Added an option to automatically loop youtube videos (default true) and code updated to work with Customizr-Pro 1.2+ and Customizr 3.4+
Updated April 2015: Added an option to prevent the related videos showing (youtube).
Updated March 2015: Added unmute on hover. This snippet works also with Customizr-Pro
Hi,
This quite advanced code snippet allows you to replace a slide of any Customizr slider by an embedded YouTube or Vimeo video, just like in the example above.
If you need professional video editing services, please consult FixThePhoto.
In addition, and with a few lines of javascript and CSS, it’s been made responsive and always vertically and horizontally centered (try to resize your screen to see this in action).
Under the hood, it uses a filter from the Customizr hooks API named : tc_slide_background, and it overrides the ‘oembed_fetch_url’ (from wp-includes\class-oembed.php) to optionally add the autoplay and loop parameters to your video, which unfortunately are not built-in WordPress options.
You can set 9 parameters in the code :
- the name of the slider (tne one choosen when creating your slider)
- the slide position in the slider. Set 1 for the first slide, 2 for the second and so on.
- the url of the video (not the embedding code, just the url which looks like : ‘http://player.vimeo.com/video/39312923’)
- autoplay : true = will be played on load
- mute volume : true = volume set to 0
- unmute on hover: true = the video will unmute on mouse hover
- pause on slide : true = the video will paused when not visible
- related videos : false = will not show related videos on playing end (youtube ONLY)
- yt_video : true = will loop youtube video
As for all code snippet, you need to paste it in your functions.php file.
Bonus : if you uncomment the $_video array, you’ll have a beautiful random from a selection of Vimeo + YouTube videos, like in the slider above this snippet.
add_filter('tc_slide_background' , 'set_video_slider', 10, 4); function set_video_slider($_original_bg , $link, $id, $s_name ) { //////////////// Parameters : //////////////// $my_slider_name = 'slider';//set the name you have choosen when creating your slider $slide_position = 1; //<= this will replace the first slide $_video = 'https://www.youtube.com/watch?v=oUlLeDKPCYA';//<=the url of your vimeo or youtube video $_autoplay = true;//<= true = autoplay $_mute_volume = true;// true = volume set to 0 $_unmute_on_hover = true;//true = the video will unmute on mouse hover $_pause_on_slide = true;//true = the video is paused on slide change $_related_videos = false;// true = display related videos . Works just with youtube videos, vimeo doesn't allow this for non premium users. $_yt_loop = true; ////////////////////////////////////////////// //uncomment this video array to run the random video //$_video = array( 'https://www.youtube.com/watch?v=oUlLeDKPCYA' , 'http://vimeo.com/108792063', 'http://vimeo.com/73373514', 'http://vimeo.com/39312923', 'http://vimeo.com/108104171', 'http://vimeo.com/106535324' , 'http://vimeo.com/108138933', 'http://vimeo.com/107789364', 'http://vimeo.com/107580451' ); $sliders = tc__f('__get_option' , 'tc_sliders'); //remove previous filter if set remove_filter('embed_oembed_html', '_add_an_id_for_youtube_player' , 10, 4); remove_filter('oembed_result' , 'enable_youtube_jsapi'); remove_filter('oembed_result' , 'set_youtube_autoplay'); remove_filter('oembed_fetch_url' , 'set_vimeo_url_query_args'); if ( $my_slider_name != $s_name ) return $_original_bg; $_slides = array(); foreach ($sliders[$s_name] as $_sid) { $_slides[] = $_sid; } if ( $id != $_slides[$slide_position-1] ) return $_original_bg; if ( ! is_array($_video) ) { $_return_video = $_video; } else { $rand_key = array_rand($_video, 1); $_return_video = $_video[$rand_key]; } //youtube or vimeo? $_provider = ( false !== strpos($_return_video, 'youtube') ) ? 'youtube' : false; $_provider = ( false !== strpos($_return_video, 'vimeo') ) ? 'vimeo' : $_provider; if ( ! $_provider ) return $_original_bg; if ( 'youtube' == $_provider ) { add_filter('embed_oembed_html', '_add_an_id_for_youtube_player' , 10, 4); //Adding parameters to WordPress oEmbed https://foxland.fi/adding-parameters-to-wordpress-oembed/ add_filter('oembed_result' , 'enable_youtube_jsapi'); if ( false !== $_autoplay ) add_filter('oembed_result' , 'set_youtube_autoplay'); if ( false !== $_yt_loop ) add_filter('oembed_result' , 'set_youtube_loop'); if ( false === $_related_videos ) add_filter('oembed_result' , 'set_youtube_no_related_videos'); } elseif ( 'vimeo' == $_provider && false !== $_autoplay ) { add_filter('oembed_fetch_url' , 'set_vimeo_url_query_args'); } //write some javascript : dynamic centering on resizing, responsiveness, Vimeo and YouTube API controls _write_video_slide_script($id, $_mute_volume, $_unmute_on_hover, $_pause_on_slide, $_provider); $_return_video = add_query_arg( 'cached' , time(), $_return_video ); //( false !== strpos($_return_video, '?') ) ? '&cached=' : '?cached='; $_return_video = apply_filters('the_content', $_return_video ); /* For someone autombed is not hooked to the content */ if ( false === strpos($_return_video, '<iframe') ){ global $wp_embed; $_return_video = $wp_embed -> autoembed( $_return_video ); } return $_return_video; } function set_vimeo_url_query_args($provider) { $provider = add_query_arg( 'autoplay', 1 , $provider ); $provider = add_query_arg( 'loop', 1 , $provider ); return $provider; } function set_youtube_autoplay($html) { if ( strstr( $html,'youtube.com/embed/' ) ) return str_replace( '?feature=oembed', '?feature=oembed&autoplay=1', $html ); return $html; } function set_youtube_loop($html) { if ( strstr( $html,'youtube.com/embed/' ) ) return preg_replace( '|(youtube.com/embed/)(.*?)(\?feature=oembed)|', '$0&loop=1&playlist=$2', $html ); return $html; } function set_youtube_no_related_videos($html) { if ( strstr( $html,'youtube.com/embed/' ) ) return str_replace( '?feature=oembed', '?feature=oembed&rel=0', $html ); return $html; } function _add_an_id_for_youtube_player($html, $url, $attr, $post_ID ) { //@to do make the id unique return str_replace('<iframe', '<iframe id="youtube-video"', $html); } function enable_youtube_jsapi($html) { if ( strstr( $html,'youtube.com/embed/' ) ) return str_replace( '?feature=oembed', '?feature=oembed&enablejsapi=1', $html ); return $html; } function _write_video_slide_script($id, $_mute_volume, $_unmute_on_hover, $_pause_on_slide, $_provider) { ?> <script type="text/javascript"> jQuery(function ($) { var $_slide_wrap = $('.slide-'+<?php echo $id ?>), $vid_iframe = $('iframe' , $_slide_wrap ), vid_height = $vid_iframe.attr('height'), vid_width = $vid_iframe.attr('width'), wind_width = $(window).width(), is_active = false, $slider_wrapper = $_slide_wrap.closest('div[id*=customizr-slider]'), $_pause_on_slide = <?php echo (true != $_pause_on_slide) ? 'false' : 'true'; ?>, $_mute_volume = <?php echo (true != $_mute_volume) ? 'false' : 'true'; ?>, $_unmute_on_hover = <?php echo (true != $_unmute_on_hover) ? 'false' : 'true'; ?>, $_provider = '<?php echo $_provider; ?>'; //$('.carousel-caption' , $_slide_wrap ).remove(); $('.carousel-image', $_slide_wrap ).css('text-align' , 'center'); //Beautify the video $('iframe' , $_slide_wrap ) .attr('width' , '').attr('height' , '') .css('width', '100%').css('max-width', '100%').css('position','relative') _re_center(); $(window).resize( function() { setTimeout(function() { _re_center();}, 200) }); function _re_center() { var new_height = (wind_width * vid_width) / vid_height, _height = $slider_wrapper.height(), push_up = (new_height - _height )/2; $('iframe' , $_slide_wrap ).css('height' , new_height ).css('bottom' , push_up ); } //VIMEO PLAYER API //http://developer.vimeo.com/player/js-api // Listen for messages from the player if (window.addEventListener){ window.addEventListener('message', onMessageReceived, false); } else { window.attachEvent('onmessage', onMessageReceived, false); } // Helper function for sending a message to the player function post(action, value, player) { if ( ! player || 0 == player.length ) return; var data = { method: action }; if (value) data.value = value; var message = JSON.stringify(data); url = player.attr('src').split('?'), player[0].contentWindow.postMessage(message, url); } //Mute volume when player is ready function onMessageReceived(e) { var data = JSON.parse(e.data), $activeSlide = $slider_wrapper.find('.czr-item.active'), $player = $('iframe[src*=vimeo]', $activeSlide ); switch (data.event) { case 'ready': ( true == $_mute_volume) && post('setVolume', +0.00001 , $player ); break; } } //EVENTS : //Unmute on hover $_mute_volume && $_unmute_on_hover && $slider_wrapper.hover( function() { post('setVolume', +0.8 , $('iframe[src*=vimeo]', $(this).find('.czr-item.active') ) ); }, function() { post('setVolume', +0.000001 , $('iframe[src*=vimeo]', $(this).find('.czr-item.active') ) ); }); // Call the API on 'slid' $slider_wrapper.on('slid', function() { ( true == $_pause_on_slide) && _pause_inactive_slides(); }); function _pause_inactive_slides() { var $activeSlide = $slider_wrapper.find('.czr-item.active'), $player = $('iframe[src*=vimeo]', $activeSlide ); //if current slide has no player. Pause all other players, else play this player if ( ! $player.length ) { $slider_wrapper.find('iframe[src*=vimeo]').each( function() { post( 'pause', false , $(this) ); }); } post( 'play', null, $player ); } //YOUTUBE PLAYER API //https://developers.google.com/youtube/iframe_api_reference //https://developers.google.com/youtube/player_parameters //http://stackoverflow.com/questions/8869372/how-do-i-automatically-play-a-youtube-video-iframe-api-muted //http://css-tricks.com/play-button-youtube-and-vimeo-api/ if ( 'youtube' == $_provider ) { var player; //important : the function onYouTubeIframeAPIReady has to be added to the window object //when wrapped in another closure window.onYouTubeIframeAPIReady = function () { player = new YT.Player('youtube-video', { events: { 'onReady': onPlayerReady //'onStateChange': onPlayerStateChange } }); } //Play and Mute volume when player is ready function onPlayerReady() { //player.playVideo(); _bind_youtube_events(); if ( true == $_mute_volume) player.mute(); else player.unMute(); } function _bind_youtube_events() { //Unmute on hover if ( $_mute_volume && $_unmute_on_hover ){ $slider_wrapper.hover( function() { if ( 0 != $('iframe[src*=youtube]', $(this).find('.czr-item.active') ).length ) player.unMute(); }, function() { if ( 0 != $('iframe[src*=youtube]', $(this).find('.czr-item.active') ).length ) player.mute(); }); } // Call the API on 'slid' $slider_wrapper.on('slid', function() { if ( true !== $_pause_on_slide) return; var $activeSlide = $slider_wrapper.find('.czr-item.active'), $player = $('iframe[src*=youtube]', $activeSlide ); //if current slide has no player. Pause all other players, else play this player if it was in pause if ( ! $player.length ) { $slider_wrapper.find('iframe[src*=youtube]').each( function() { player.pauseVideo(); }); } else if ( 2 == player.getPlayerState() ){ player.playVideo(); } });//end on slid };//end _bind_youtube_events //load the youtube API script asynchronously var tag = document.createElement('script'); tag.src = "http://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); } }); </script> <?php }
Code and resources used for this snippet :
- Vimeo player API
- YouTube player API reference
- Get the instance of an already rendered YouTube iframe
- Quick YouTube and Vimeo API setup
- Adding parameters to WordPress
I hope you’ll enjoy this one and I look forward to seeing your beautiful examples!
44 thoughts on “Embedding a YouTube or Vimeo video in your slider”
No longer works in current version of theme..
My guess is slider is now a different name thus this snippet no longer works.
Didn’t realize this was an unsupported option for the theme…
oh well – figures.
Is this possible for the free theme?
yes this snippet works with all versions of the theme
Hello Nicolas,
I’ve been trying this snippet, and I have a couple of questions for you:
1) In the _re_center() function, I feel there’s bug in the formula used to calculate new_height:
In your code:
I think it should be:
And maybe better (because slider may not be full window width):
2) It seems that Youtube filters are not applied, because the video does not autoplay, does not mute and does not have an id. I am using last version of the theme (3.2.15). I have tried to call the filters outside the “if” statements with no results.
Hi Jaume, thanks for your feedback. I need to test your 2 points.
Cheers
Hi Nicolas. How do you make the audio so that it’s muted unless the visitor mouses over the video, as in the example at the top of this page?
Hi Aaron,
to unmute on mouse hover, I have just added the following code which is fired onPlayerReady :
I hope this will help !
Does this code still apply?
Hi,
Video does not auto-repeat and therefore shows related videos at the end.
Also need to display an image only on mobile.
Also video does not mute on Chrome and does on IE.
Any way to host video on hosting instead of YouTube/Vimeo?
Any way to stop users from being able to pause?
Would love to see all these features.
Thanks for this theme.
P.S. oh there is the biggest issue I forgot lol, sometimes (and I see other have this problem above) the video says “&caching=xxxxxxxx” instead of displaying the video. It does not have to do with coding error because some videos work and some don’t.
Thanks again 🙂
Thanks John for this feedback and features request.
There’s many ! 🙂
It is hard to answer at this point but I have just included all your suggestion in my to improve list.
I appreciate your contribution,
Nicolas.
Thank you Nicolas,
I do not quite mastered programming in PHP to launch into this adventure.
I thought maybe someone will he bring me this help?
Cheers
You’ll want to open a new thread about this in the very active Customizr support forum where many Customizr’s experts might be able to answer and help :).
Hi,
Is it possible to have in the slider one only persistent video through all the slides. for example I have 4 slides in my slider with associated text for each slide. I would remplace the 4 images but of course keep the 4 texts, within the video along the show. The effect is to show the complete video in background and the text of my 4 slides in the front side.
Thanks
Hi Cedric,
Text slide only with fixed video in the background : this snippet does not cover this particular case but the current code could be a good starting point.
I would be interested by sharing the result if you manage to do it!
Cheers
Hi Nick,
Currently, everything is great except the video will not mute. Here are the current parameter settings:
$_autoplay = true;//<= true = autoplay
$_mute_volume = true;// true = volume set to 0
$_pause_on_slide = true;//true = the video is paused on slide change
Hopefully you can help fix this.
Thanks,
John
P.S. it is a YouTube video.
Thanks for sharing! 🙂
The following parameters not working:
// Add video to slider
add_filter(‘tc_slide_background’ , ‘set_video_slider’, 10, 4);
function set_video_slider($_original_bg , $link, $id, $s_name ) {
//////////////// Parameters : ////////////////
$my_slider_name = ‘homepage-slider’;//set the name you have choosen when creating your slider
$slide_position = 1; //<= this will replace the first slide
$_video = 'https://www.youtube.com/watch?v=oUlLeDKPCYA';//<=the url of your vimeo or youtube video
$_autoplay = true;//<= true = autoplay
$_mute_volume = true;// true = volume set to 0
$_pause_on_slide = true;//true = the video is paused on slide change
//////////////////////////////////////////////
//uncomment this video array to run the random video
//$_video = array( 'https://www.youtube.com/watch?v=oUlLeDKPCYA' , 'http://vimeo.com/108792063', 'http://vimeo.com/73373514', 'http://vimeo.com/39312923', 'http://vimeo.com/108104171', 'http://vimeo.com/106535324' , 'http://vimeo.com/108138933', 'http://vimeo.com/107789364', 'http://vimeo.com/107580451' );
*******************************************
In our functions.php we have "htmlified" our slider, and in CSS we have increased slider height to 600px.
Could these be the reason why the video is not working?
Neither "homepage-slider" nor "homepage slider" work and that is the name of our slider.
Thanks,
Moh
Scratch that, video is working but volume mute paramater still not working and most importantly, would be great to have the regular slider image replace the video automatically on mobile as it currently does not autoplay on mobile plus opens in new screen = no good.
If you know how to replace video with regular slider image on mobile do let me know (surely this will help others as well).
Thank you
Ok thanks for the feedback and for your suggestion 🙂
I’ll let you know when I’ll found a stable solution.
Cheers
Hi Nick, I have tried to use your code here, I copied and pasted it into my functions.php on the wordpress editor, entered the urls for the videos and slider number of what I’d like to show and I get NO videos showing, I’m only getting the images in the slider, no videos… HELP?
What am i doing wrong?
Hi Jessica,
It’s hard to say without seeing your exact code and how you have pasted it. But it seems it is not taken into account from what you are describing…
Cheers
Hi Nicholas,
This looks like an awesome feature and I’m hoping to start using it in the next couple of weeks. One question – is it possible to have both a background image and a video appearing together? I’m imagining a full-width, centred image and the video to the right of the call to action, so that it doesn’t distract from the CTA.
Thanks,
Jacqui
Hi Jacqui,
This is a good idea. This would require some modifications to the original code.
Feel free to push some changes on the original snippet : https://gist.github.com/Nikeo/2575143b9898b240f590#file-embedding-video-in-your-customizr-slider-php
Thanks,
Nicolas.
Nicolas,
I haven’t been able to get this code to work at all. Like two other people who have posted here I am getting the following when I visit my site, “https://www.youtube.com/watch?v=o-AbEO6J8s0&cached=1418937638”. Do you think it is because I am running version 3.2? Does this work with Customizr Pro? If you could please address this it would be greatly appreciated. Thank you for your time and consideration. Cheers
Has anyone figured out how to stop related videos from showing.
tried adding parameter
tried adding &rel=0 and ?rel=0
neither work.
Thanks
If i want to do this for more than one page and more than one slider do i just duplicate the entire code?
Thanks
Hi, a possibility would be to use the slider name to determine which parameter have to be used…
HI Nicolas,
Thank you, can you point me in the direction of where i need to implement that change. How can i do this?
Thanks
I recognize some of the spots where I need to add in my specific coding/youtube information, but how to I know exactly where I need to add in any other information or what I actually need to cut and paste for the CSS to work? I can’t tell exactly what is instructions and what is actual coding in some spots. all the // are slightly confusing me. Sorry for my ignorance. Thank you for your time.
Hi,
If you are new to WordPress coding, you’ll want to read this post on how to customize the Customizr theme.
Hope this helps!
Hi Nicolas,
As for Jon, it was working nicely, then the source code came (https://www.youtube.com/watch?v=oUlLeDKPCYA&cached=1417963185) instead of the image. How is that possible? I’ve copied and pasted it again, but no changes.
I just do not understand what went wrong, considering that I didn’t change your filter at all…
All my best wishes
This code snippet is awesome! Is there anyway to remove the youtube video links after the video ends?
Adding the “?rel=0” after the video link usually does the trick but it doesnt seem to work here. I’m pretty sure I’m not putting it in the right spot.
Normal Working Example:
Thank you!
I did not test this but I am sure there must be an easy way with the API !
cheers
Hello,
Can you help me…I’m having this error
Warning: Missing argument 4 for set_video_slider()
Hi Ganfall, you’ll want to check if you have properly setup all function arguments.
(Note : this snippet requires quite advanced skills in php, you’ll want to make sure you fully understand how the php functions arguments and how to change theme php functions )
my autoplay is set to true but the video does not autoreplay ….its a 14 sec video ….
How can i set the video on autoreplay?
Hi,
In the above code, setting autoplay to true will also add the loop=1 (auto replay) parameter in the query arg.
Cheers.
Hi Nic,
Excellent snippet and am very excited to use it. It was working excellently for me whilst I was developing my site. However it is now returning a messages such as:
https://www.youtube.com/watch?v=oUlLeDKPCYA&cached=1415436328
Where it once showed the video.
Any ideas?
Kind regards,
Jon
Hi Nicolas,
Thanks for the advice. I wasn’t talking about some bug though. It also shows a black screen on my Android phone. The movie will not be played. I read somewhere this is not a bug, but a feature. Mobile browsers aren’t capable of using autoplay, because this might result in unwanted high costs for 3G connections.
So, to overcome this problem I would like to show a normal slide image (placeholder) on mobile devices instead. Since I use your wonderful video slider as a banner, it seems a bit weird having to start a banner manually to me. The lazy video plugin is nice, but disables the autoplay feature. The whole thing I want to achieve is an awesome UX by showing a cool background video that plays automatically. For mobile users I will except a fallback option by just showing some awesome images instead.
Hope my problem is clear now. My guess is I am not the only one looking for this solution. Some how this website just skips showing the banner as a whole on my mobile. How did you achieve this?
One last thing. Do you happen to know how to disable the video suggestions Youtube gives after playing the total movie?
Thanks again!
Casper
Hi Nicolas, let’s start by saying I absolutely love the Customizr theme. It is awesome. I am totally new to Wordpress (just started a few weeks ago), but your theme is really easy to customize so far. On top of that, I love this website. I taught me a lot about the functionalities of Wordpress, CSS and even PHP is starting to become more clear now. Great job!
Currently I am playing aroung with some stuff to see how it works. Using your code snippet above I got a full width video playing without a problem. Unfortunately I found out that the “autoplay” feature is not supported on mobile browsers. So now this leaves a black page when looking on my mobile. Could you give any advice on how to show a placeholder image instead? I have been Googling this for hours now, but can’t find out how to do this. It is either not the right solution, or technically over my head (still).
Thanks for your time!
Casper
Hi Casper,
There’s apparently an unresolved issue on the Vimeo player.js with iOS devices (iphones, ipads).
A work around would be to disable the autoplay feature only for those specific devices with a snippet like the following :
if ( ! empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false )
$autoplay = false;
Hope this helps and thanks for comment!
Placeholder image : there’s a plugin named lazy load for video that does this placeholder job for you.