{"id":46,"date":"2019-11-18T11:18:11","date_gmt":"2019-11-18T17:18:11","guid":{"rendered":"https:\/\/travisolson.net\/code\/?p=46"},"modified":"2021-08-02T09:12:19","modified_gmt":"2021-08-02T14:12:19","slug":"wordpress-post-load-youtube-videos","status":"publish","type":"post","link":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/","title":{"rendered":"WordPress: Post-load YouTube Videos"},"content":{"rendered":"<p>Embedding YouTube videos directly into your page can increase the load time significantly, especially when multiple videos are embedded. One solution is to load thumbnail images instead, and then load the videos only when clicked.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">\/* Generate post-load HTML wrapper for a YouTube video. *\/\r\nfunction myprefix_youtube_postload($youtube_id, $thumb_size = 'hq') {\r\n  $thumb_sizes = array(\r\n    'hq' =&gt; 'hqdefault', \/\/ 480x360\r\n    'sd' =&gt; 'sddefault', \/\/ 640x480\r\n    'med' =&gt; 'mqdefault', \/\/ 320x180\r\n    'max' =&gt; 'maxresdefault' \/\/ 1920x1080\r\n  );\r\n  if (!in_array($thumb_size, array_keys($thumb_sizes))) {\r\n    $thumb_size = 'hq';\r\n  }\r\n  $html = '&lt;div class=\"youtube postload\" data-embedid=\"'.esc_attr($youtube_id).'\" data-thumbsize=\"'.esc_attr($thumb_sizes[$thumb_size]).'\"&gt;&lt;div class=\"play-button\"&gt;&lt;\/div&gt;&lt;\/div&gt;';\r\n  return $html;\r\n}<\/pre>\n<p>The above function doesn&#8217;t do much by itself. The most important parts are the &#8220;postload&#8221; class and the two data attributes, which will be used by JavaScript to load the thumbnail and video.<\/p>\n<p>In a JavaScript file, add the following code. You may need to enqueue a new script if you don&#8217;t already have one available for editing.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">jQuery(document).ready(function($) {\r\n  \/* Lazy-load YouTube videos.  This uses mostly non-jQuery code because that's what we copied from\r\n   * the source: https:\/\/webdesign.tutsplus.com\/tutorials\/how-to-lazy-load-embedded-youtube-videos--cms-26743\r\n   * This might lead to some cross-browser compatiblity issues, but should run faster than jQuery.\r\n   * If we have browser issues, just migrate this to jQuery.\r\n   * One major change is the use of a background image for the thumbnail instead of creating an\r\n   * img element.  This allows for easier vertical centering and positioning.\r\n   *\/\r\n  var youtubes = document.querySelectorAll( \".youtube.postload\" );\r\n  for (var i = 0; i &lt; youtubes.length; i++) {\r\n    \/* Load the thumbnail as background image, using selected size *\/\r\n    var source = \"https:\/\/img.youtube.com\/vi\/\"+ youtubes[i].dataset.embedid +\"\/\"+youtubes[i].dataset.thumbsize+\".jpg\";\r\n    youtubes[ i ].addEventListener( \"load\", function() {\r\n      youtubes[ i ].style.backgroundImage = \"url('\"+source+\"')\";\r\n    }( i ) );\r\n    \r\n    \/* Add click events to all of the elements to load the iframe *\/\r\n    youtubes[i].addEventListener( \"click\", function() {\r\n      var iframe = document.createElement( \"iframe\" );\r\n    \r\n      iframe.setAttribute( \"frameborder\", \"0\" );\r\n      iframe.setAttribute( \"webkitallowfullscreen\", \"webkitallowfullscreen\" );\r\n      iframe.setAttribute( \"mozallowfullscreen\", \"mozallowfullscreen\" );\r\n      iframe.setAttribute( \"allowfullscreen\", \"allowfullscreen\" );\r\n      iframe.setAttribute( \"src\", \"https:\/\/www.youtube.com\/embed\/\"+ this.dataset.embedid +\"?rel=0&amp;showinfo=0&amp;autoplay=1\" );\r\n    \r\n      this.innerHTML = \"\";\r\n      this.appendChild( iframe );\r\n    } );\r\n  }\r\n});<\/pre>\n<p>You&#8217;ll need to add some styles to display a play button over top of the thumbnails. These styles can be changed to fit your needs.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"css\">.youtube {\r\n  display: block;\r\n  margin:0;\r\n  background-color: #000;\r\n  position: relative;\r\n  overflow: hidden;\r\n  cursor: pointer;\r\n  background-size:100% auto;\r\n  background-position:0 center;\r\n  background-repeat:no-repeat;\r\n  width:335px;\r\n  max-width: 100%;\r\n  height:200px;\r\n}\r\n.youtube img {\r\n  width: 100%;\r\n  top: -16.84%;\r\n  left: 0;\r\n  opacity: 0.7;\r\n}\r\n.youtube .play-button {\r\n  width: 90px;\r\n  height: 60px;\r\n  background-color: #333;\r\n  box-shadow: 0 0 30px rgba( 0,0,0,0.6 );\r\n  z-index: 1;\r\n  opacity: 0.8;\r\n  border-radius: 6px;\r\n}\r\n.youtube .play-button:before {\r\n  content: \"\";\r\n  border-style: solid;\r\n  border-width: 15px 0 15px 26.0px;\r\n  border-color: transparent transparent transparent #fff;\r\n}\r\n.youtube img,\r\n.youtube .play-button {\r\n  cursor: pointer;\r\n}\r\n.youtube img,\r\n.youtube iframe,\r\n.youtube .play-button,\r\n.youtube .play-button:before {\r\n  position: absolute;\r\n}\r\n.youtube .play-button,\r\n.youtube .play-button:before {\r\n  top: 50%;\r\n  left: 50%;\r\n  transform: translate3d( -50%, -50%, 0 );\r\n}\r\n.youtube iframe {\r\n  height: 100%;\r\n  width: 100%;\r\n  top: 0;\r\n  left: 0;\r\n}<\/pre>\n<p>Now you can call the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">myprefix_youtube_postload()<\/code> function to output the thumbnail in your code. All you need to pass is the YouTube ID and the optional thumbnail size.\u00a0 If you are using data that is input in the back-end by the end-user, it is probably a good idea to make sure they aren&#8217;t pasting the full YouTube URL into that data field.\u00a0 You can use the following to extract the YouTube ID from user input, if necessary. It will attempt to extract the ID from commonly-used YouTube URLs.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">function myprefix_extract_youtube_id($url) {\r\n  preg_match(\"\/^(?:http(?:s)?:\\\/\\\/)?(?:www\\.)?(?:m\\.)?(?:youtu\\.be\\\/|youtube\\.com\\\/(?:(?:watch)?\\?(?:.*&amp;)?v(?:i)?=|(?:embed|v|vi|user)\\\/))([^\\?&amp;\\\"'&gt;]+)\/\", $url, $matches);\r\n  return $matches[1];\r\n}<\/pre>\n<p>You can also create a shortcode to utilize this functionality in your posts\/pages:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">function myprefix_youtube_embed_shortcode($atts) {\r\n  if (!isset($atts['id'])) {\r\n    return false;\r\n  }\r\n  return myprefix_youtube_postload($atts['id'], $atts['thumb_size']);\r\n}\r\n\r\nfunction myprefix_shortcode_plugins_loaded() {\r\n  add_shortcode( 'myprefix_youtube_embed', 'myprefix_youtube_embed_shortcode' );\r\n}\r\nadd_action( 'plugins_loaded', 'myprefix_shortcode_plugins_loaded' );<\/pre>\n<p>Then you can simply use a shortcode such as <code class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">[myprefix_youtube_embed id=\"abcd1234\"]<\/code>\u00a0to embed the video.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Embedding YouTube videos directly into your page can increase the load time significantly, especially when multiple videos are embedded. One solution is to load thumbnail images instead, and then load the videos only when clicked. \/* Generate post-load HTML wrapper for a YouTube video. *\/ function myprefix_youtube_postload($youtube_id, $thumb_size = &#8216;hq&#8217;) { $thumb_sizes = array( &#8216;hq&#8217;&#8230;  <a class=\"excerpt-read-more\" href=\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/\" title=\"Read WordPress: Post-load YouTube Videos\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-46","post","type-post","status-publish","format-standard","hentry","category-wordpress"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>WordPress: Post-load YouTube Videos - Travis Olson&#039;s Code Snippets<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"WordPress: Post-load YouTube Videos - Travis Olson&#039;s Code Snippets\" \/>\n<meta property=\"og:description\" content=\"Embedding YouTube videos directly into your page can increase the load time significantly, especially when multiple videos are embedded. One solution is to load thumbnail images instead, and then load the videos only when clicked. \/* Generate post-load HTML wrapper for a YouTube video. *\/ function myprefix_youtube_postload($youtube_id, $thumb_size = &#039;hq&#039;) { $thumb_sizes = array( &#039;hq&#039;... Read more &raquo;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/\" \/>\n<meta property=\"og:site_name\" content=\"Travis Olson&#039;s Code Snippets\" \/>\n<meta property=\"article:published_time\" content=\"2019-11-18T17:18:11+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-08-02T14:12:19+00:00\" \/>\n<meta name=\"author\" content=\"Travis Olson\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Travis Olson\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/\"},\"author\":{\"name\":\"Travis Olson\",\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934\"},\"headline\":\"WordPress: Post-load YouTube Videos\",\"datePublished\":\"2019-11-18T17:18:11+00:00\",\"dateModified\":\"2021-08-02T14:12:19+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/\"},\"wordCount\":241,\"publisher\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934\"},\"articleSection\":[\"WordPress\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/\",\"url\":\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/\",\"name\":\"WordPress: Post-load YouTube Videos - Travis Olson&#039;s Code Snippets\",\"isPartOf\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/#website\"},\"datePublished\":\"2019-11-18T17:18:11+00:00\",\"dateModified\":\"2021-08-02T14:12:19+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.travisolson.net\/code\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"WordPress: Post-load YouTube Videos\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.travisolson.net\/code\/#website\",\"url\":\"https:\/\/www.travisolson.net\/code\/\",\"name\":\"Travis Olson&#039;s Code Snippets\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.travisolson.net\/code\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934\",\"name\":\"Travis Olson\",\"logo\":{\"@id\":\"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/image\/\"},\"url\":\"https:\/\/www.travisolson.net\/code\/author\/travis-olson\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"WordPress: Post-load YouTube Videos - Travis Olson&#039;s Code Snippets","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/","og_locale":"en_US","og_type":"article","og_title":"WordPress: Post-load YouTube Videos - Travis Olson&#039;s Code Snippets","og_description":"Embedding YouTube videos directly into your page can increase the load time significantly, especially when multiple videos are embedded. One solution is to load thumbnail images instead, and then load the videos only when clicked. \/* Generate post-load HTML wrapper for a YouTube video. *\/ function myprefix_youtube_postload($youtube_id, $thumb_size = 'hq') { $thumb_sizes = array( 'hq'... Read more &raquo;","og_url":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/","og_site_name":"Travis Olson&#039;s Code Snippets","article_published_time":"2019-11-18T17:18:11+00:00","article_modified_time":"2021-08-02T14:12:19+00:00","author":"Travis Olson","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Travis Olson","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/#article","isPartOf":{"@id":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/"},"author":{"name":"Travis Olson","@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934"},"headline":"WordPress: Post-load YouTube Videos","datePublished":"2019-11-18T17:18:11+00:00","dateModified":"2021-08-02T14:12:19+00:00","mainEntityOfPage":{"@id":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/"},"wordCount":241,"publisher":{"@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934"},"articleSection":["WordPress"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/","url":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/","name":"WordPress: Post-load YouTube Videos - Travis Olson&#039;s Code Snippets","isPartOf":{"@id":"https:\/\/www.travisolson.net\/code\/#website"},"datePublished":"2019-11-18T17:18:11+00:00","dateModified":"2021-08-02T14:12:19+00:00","breadcrumb":{"@id":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.travisolson.net\/code\/wordpress-post-load-youtube-videos\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.travisolson.net\/code\/"},{"@type":"ListItem","position":2,"name":"WordPress: Post-load YouTube Videos"}]},{"@type":"WebSite","@id":"https:\/\/www.travisolson.net\/code\/#website","url":"https:\/\/www.travisolson.net\/code\/","name":"Travis Olson&#039;s Code Snippets","description":"","publisher":{"@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.travisolson.net\/code\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/0170ab5b2e7a3d88436375cc50336934","name":"Travis Olson","logo":{"@id":"https:\/\/www.travisolson.net\/code\/#\/schema\/person\/image\/"},"url":"https:\/\/www.travisolson.net\/code\/author\/travis-olson\/"}]}},"_links":{"self":[{"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/posts\/46","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/comments?post=46"}],"version-history":[{"count":4,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/posts\/46\/revisions"}],"predecessor-version":[{"id":61,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/posts\/46\/revisions\/61"}],"wp:attachment":[{"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/media?parent=46"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/categories?post=46"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.travisolson.net\/code\/wp-json\/wp\/v2\/tags?post=46"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}