Display YouTube video view counts in the WordPress Grid Gallery


WonderPlugin Portfolio Grid Gallery


I have a grid gallery of YouTube videos. I want to show the number of video views served from YouTube. Is this possible?


This tutorial will guide you how to show the YouTube video view counts in the grid gallery.

Step 1 - Apply for your own Google API key for YouTube

Please view this tutorial and apply for your own Google API key for YouTube: https://www.wonderplugin.com/wordpress-tutorials/how-to-apply-for-a-google-api-key-for-youtube/

Step 2 - Add Custom JavaScript code to get the YouTube views and display it in the grids

In the plugin, step 4, Options tab, Advanced Options, add the following JavaScript code to the Custom JavaScript input box.

The third line of the code is our YouTube API key: var apikey = "AIzaSyBVMaKX36bG2mxLUGGV9YbVaWCsvfbikJQ";. The key only works on our website, so please make sure to change the value to your own key.

(function($) {
  $(document).ready(function() {
    var apikey = "AIzaSyBVMaKX36bG2mxLUGGV9YbVaWCsvfbikJQ";
    $(".wonderplugin-gridgallery-item").each(function() {
      var griditem = $(this);
      var link = griditem.find("a");
      if (link.length && link.attr("href"))
        var href = link.attr("href");
        if (href.indexOf("youtube") >= 0)
          var youtubeid = "";
          var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\??v?=?))([^#\&\?]*).*/;
          var match = href.match(regExp);
          if ( match && match[7] && (match[7].length==11) )
            youtubeid = match[7];
          if (youtubeid)
            $.getJSON("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" + youtubeid + "&key=" + apikey, function(data) {
              var count = data.items[0].statistics.viewCount;
              griditem.find(".wonderplugin-gridgallery-item-title").append("<br>" + count + " Views");

A demo is as follows: