Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

Display YouTube Videos, Video Views and other Data with PHP or WordPress Shortcode

Display YouTube Videos, Video Views and other Data with PHP or WordPress Shortcode

This article provides the necessary code to render YouTube video views, titles, descriptions, likes, dislikes, and other data into your WordPress website or PHP application with shortcode. The functions require that you register for an API key via Google's Developer Console .

Both the WordPress and PHP function share a single function that makes the request for video data and then caches the result. Since we cache all information returned by YouTube, we require installation of Simple Cache (available as WP plugin) so repeated requests aren't made for the same data. Using Simple Cache also permits you to style various results without multiple requests, and the data is also available from your other applications and websites. We do, however, cache the styled container we build as a WP transient.

Sample Result

A simple example of returned data in a styled container is as follows. We've used our very dodgy blind shortcode for the share link. It's expected that the container will be rendered below a video.

Boeing 777 Engine Failure during Takeoff
4,827,778 views

Published on September 14, 2012. Demonstration of an engine failure during the takeoff roll in a Boeing 777. This video was produced for the CRM/NTS training environment so, as such, doesn't necessarily demonstrate or reflect best operating or SOP compliant practices. These videos were produced for exclusive use by BeliefMedia.
631 6,029 1,275

The container we've built takes up a little real-estate, so you may want to include all the information in a blind as shown below. We've included the Simple Cache video for the purpose of the demo.

PHP Function

The following PHP function makes the request for YouTube data and caches the result as a serialized array with Simple Cache.

1
<?php 
2
/*
3
 Display YouTube Videos, Video Views and other Data with PHP or WordPress Shortcode
4
 http://www.beliefmedia.com/youtube-video-data
5
*/
6
 
7
function beliefmedia_youtube_video_data($v = 'C7O7R_Vk7Ko', $cache = '14400') {
8
 
9
 /* API Key */
10
 $apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
11
 
12
 /* Get transient data */
13
 $transient = 'youtube_video_data_' . md5(serialize(func_get_args()));
14
 $response = beliefmedia_get_transient($transient, $cache);
15
 
16
 if ($response !== false)  {
17
 
18
   return $response;
19
 
20
    } else {
21
 
22
     $json_string = @file_get_contents('https://www.googleapis.com/youtube/v3/videos?part=statistics,contentDetails,snippet&id=' . $v . '&key=' . $apikey);
23
     if ($json_string !== false) $response = json_decode($json_string, true);
24
 
25
      if (count($response) != 0) {
26
 
27
        /* Cache the array */
28
        beliefmedia_set_transient($transient, $response);
29
        return $response;
30
 
31
         } else {
32
 
33
        /* We'll keep the old data until the API behaves */
34
        $result = beliefmedia_get_transient_data($transient);
35
        return (count($result) != '0') ? $result : false;
36
       }
37
   }
38
}

With the video array cached, you simply need to retrieve the resulting array via beliefmedia_get_transient($transient, $cache) and format the results to your liking.

WordPress Shortcode

The shortcode example is minimal. Usage is as follows: [youtube_video v="C7O7R_Vk7Ko"].

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)
4
 Builds sample container for data.
5
 http://www.beliefmedia.com/youtube-channel-data
6
*/
7
 
8
9
 
10
  $atts = shortcode_atts(array(
11
    'v' => 'C7O7R_Vk7Ko',
12
    'width' => '540px',
13
    'bordercolor' => '#DA0000', // #F1F1F1
14
    'borderwidth' => '1',
15
    'cache' => 3600 * 24 * 3
16
  ), $atts);
17
 
18
  $transient = 'ytdatas_' . md5(serialize($atts));
19
 
20
  $cached = get_transient($transient);
21
  if ($cached !== false) {
22
    return $cached;
23
 
24
  } else {
25
 
26
     /* Get video data (returns array of all data) */
27
     $data = beliefmedia_youtube_video_data($atts['v'], $atts['cache']);
28
 
29
     /* Data */
30
     $title = $data['items']['0']['snippet']['title'];
31
     // $description = beliefmedia_youtube_description($data['items']['0']['snippet']['description'], $sentences = 2);
32
 
33
     /* Sample container */
34
     $return = '<div style="width: ' . $atts['width'] . '; max-width: 95%; border: ' . $atts['bordercolor'] . ' ' . abs($atts['borderwidth']) . 'px solid; padding: 10px 10px 3px 10px; color: #000000; background-color: #ffffff; margin: 0 auto;">
35
<div>
36
<div style="font-size: 1.1em; padding-left: 15px; font-weight: bold;">' . $title . '</div>
37
<div style="color: #000000; padding: 30px 15px 5px 15px; float: right; font-size: 1.1em; font-weight: bold;">' . number_format($data['items']['0']['statistics']['viewCount']) . ' views</div>
38
<div style="color: #000000; padding: 8px 30px 8px 65px; background: #ffffff url(http://www.beliefmedia.com/wp-images/site/textbox/yt40.png) no-repeat 10px 50%; font-weight: bold;"><a href="https://www.youtube.com/channel/' . $data['items']['0']['snippet']['channelId'] . '" target="_blank" rel="noopener noreferrer">' . $data['items']['0']['snippet']['channelTitle'] . '</a><div class="g-ytsubscribe" data-channelid="' . $data['items']['0']['snippet']['channelId'] . '" data-layout="default" data-count="default"></div>
39
</div></div>
40
</p></div>';
41
 
42
     /* Set transient */
43
     set_transient($transient, $return, $atts['cache']);
44
 
45
   /* Return new result */
46
   return $return;
47
 }
48
}
49
add_shortcode('youtube_video', 'beliefmedia_youtube_video_meta_simple');

The result:

Boeing 777 Engine Failure during Takeoff
4,827,868 views

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Return Video Views, Thumbnails, and Other Information

There are times when you will need to return specific pieces of video information. For example, the shortcode of [ytdata v="C7O7R_Vk7Ko" type="views"] returns 4,827,868. You could optionally return the number or likes, dislikes, comments, or the publish date, title, or description. Each piece of data is returned by altering the type attribute in the shortcode. For example, [ytdata v="C7O7R_Vk7Ko" type="published"] returns September 14, 2012. You may optionally return a full constructed thumbnail image. For example, [ytdata v="C7O7R_Vk7Ko" type="thumbnail_high"] returns:

Boeing 777 Engine Failure during Takeoff

The black bars can be removed with a little post processing but it's beyond the scope of our simple function. Alter the code if you'd like the image to link to the video.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)
4
 Return specific information & video thumbnail images
5
 http://www.beliefmedia.com/youtube-channel-data
6
*/
7
 
8
9
 
10
  $atts = shortcode_atts(array(
11
    'v' => 'C7O7R_Vk7Ko',
12
    'type' => 'views',
13
    'date' => 'F j, Y',
14
    'cache' => 3600 * 24 * 3
15
  ), $atts);
16
 
17
  $transient = 'ytdatas_' . md5(serialize($atts));
18
 
19
  $cached = get_transient($transient);
20
  if ($cached !== false) {
21
    return $cached;
22
 
23
  } else {
24
 
25
     /* Get video data (returns array of all data) */
26
     $data = beliefmedia_youtube_video_data($atts['v'], $atts['cache']);
27
 
28
     switch ($atts['type']) {
29
         case 'views':
30
             $return = number_format($data['items']['0']['statistics']['viewCount']);
31
             break;
32
         case 'likes':
33
             $return = number_format($data['items']['0']['statistics']['likeCount']);
34
             break;
35
         case 'dislikes':
36
             $return = number_format($data['items']['0']['statistics']['dislikeCount']);
37
             break;
38
         case 'comments':
39
             $return = number_format($data['items']['0']['statistics']['commentCount']);
40
             break;
41
         case 'published':
42
             $return = date($atts['date'], strtotime($data['items']['0']['snippet']['publishedAt']));
43
             break;
44
         case 'title':
45
             $return = $data['items']['0']['snippet']['title'];
46
             break;
47
         case 'description':
48
             $return = $data['items']['0']['snippet']['description'];
49
             break;
50
         case 'thumbnail_small':
51
             $return = $data['items']['0']['snippet']['thumbnails']['default']['url'];
52
             $return = '<img loading="lazy" src="' . $return . '" alt="' . $data['items']['0']['snippet']['title'] . '" title="' . $data['items']['0']['snippet']['title'] . '" width="120" height="90" class="aligncenter size-full wp-image-ytthumb" />';
53
             break;
54
         case 'thumbnail_medium':
55
             $return = $data['items']['0']['snippet']['thumbnails']['medium']['url'];
56
             $return = '<img loading="lazy" src="' . $return . '" alt="' . $data['items']['0']['snippet']['title'] . '" title="' . $data['items']['0']['snippet']['title'] . '" width="320" height="180" class="aligncenter size-full wp-image-ytthumb" />';
57
             break;
58
         case 'thumbnail_high':
59
             $return = $data['items']['0']['snippet']['thumbnails']['high']['url'];
60
             $return = '<img loading="lazy" src="' . $return . '" alt="' . $data['items']['0']['snippet']['title'] . '" title="' . $data['items']['0']['snippet']['title'] . '" width="480" height="360" class="aligncenter size-full wp-image-ytthumb" />';
61
             break;
62
         case 'thumbnail_standard':
63
             $return = $data['items']['0']['snippet']['thumbnails']['standard']['url'];
64
             $return = '<img loading="lazy" src="' . $return . '" alt="' . $data['items']['0']['snippet']['title'] . '" title="' . $data['items']['0']['snippet']['title'] . '" width="640" height="480" class="aligncenter size-full wp-image-ytthumb" />';
65
             break;
66
         case 'thumbnail_maxres':
67
             $return = $data['items']['0']['snippet']['thumbnails']['maxres']['url'];
68
             $return = '<img loading="lazy" src="' . $return . '" alt="' . $data['items']['0']['snippet']['title'] . '" title="' . $data['items']['0']['snippet']['title'] . '" width="1280" height="720" class="aligncenter size-full wp-image-ytthumb" />';
69
             break;
70
         default:
71
             $return = $data['items']['0']['statistics']['viewCount'];
72
             break;
73
     }
74
 
75
     /* Set transient */
76
     set_transient($transient, $return, $atts['cache']);
77
 
78
   /* Return result */
79
   return $return;
80
 }
81
}
82
add_shortcode('ytdata', 'beliefmedia_youtube_video_data_thumbnails');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

The function requires beliefmedia_youtube_video_data() and Simple Cache.

Shortcode Attributes are as follows:

v

The video ID.

type

The type of data to be returned. Options are: views, likes, dislikes, comments, published, title, description, thumbnail_small (120 x 90), thumbnail_medium (320 x 180), thumbnail_high (480 x 360), thumbnail_standard (640 x 480), thumbnail_maxres (1280 x 720).

date

The date format. Formatting can be constructed by way of information in the PHP manual .

cache

The time to cache the result.

An advantage of using Simple Cache is that YouTube data is cached for a period as defined by you. Requests for array values won't make unnecessary requests to YouTube after the first request is made. When a new request is made for data (as defined by the cache period in Simple Cache) and the API request doesn't return a response, old data will instead be recycled.

Considerations

  • A sample array returned by YouTube is published here. To view the data returned via your own request, use the following:

    1
    $result = beliefmedia_get_transient_data($transient);
    2
    echo print_r($result, true);
  • In our more complete example we snip the description by sentence length. To snip the description by length we have a number of options here. A function to return only a certain number of sentences is as follows:
    1
    <?php 
    2
    /*
    3
     Display YouTube Videos, Video Views and other Data with PHP or WordPress Shortcode
    4
     http://www.beliefmedia.com/youtube-video-data
    5
     Function returns a number of sentences
    6
    */
    7
     
    8
    function beliefmedia_youtube_description($text, $sentences = false) {
    9
     
    10
      /* Remove breaks */
    11
      $text = preg_replace( "/\r|\n/", ' ', $text);
    12
     
    13
      /* How many sentences in the text? */
    14
      $lines = preg_split('/(?<=[.?!])\s+(?=[a-z])/i', $text);
    15
     
    16
      if ( ($sentences !== false) && ($sentences < count($lines)) ) {
    17
        $i = 0;
    18
        while ($i <= $sentences) {
    19
          $result .= trim($lines["$i"]) . ' ';
    20
          $i++;
    21
        }
    22
     
    23
       return trim($result);
    24
      }
    25
     
    26
     else return trim($text);
    27
    }

    Rather than loop through the array as we've done, you might consider using array_slice() .

  • Our featured meta box includes share icons for just a few websites. We used a function similar to the one below. To add additional icons, simply add them to the list. While we add the YouTube URL as the link, you may want to alter this in WordPress to your post permalink.
    1
    <?php 
    2
    /*
    3
     Display YouTube Videos, Video Views and other Data with PHP or WordPress Shortcode
    4
     http://www.beliefmedia.com/youtube-video-data
    5
     Returns share icons and links
    6
    */
    7
     
    8
    function beliefmedia_youtube_share($v, $title, $description = '', $twitter_related, $twitter_via) {
    9
     
    10
      $return = '<a href="https://twitter.com/intent/tweet?url=' . urlencode('https://youtu.be/' . $v) . '&text=' . urlencode($title) . '&via=' . $twitter_via . '&related=' . $twitter_related . '"><img src="wp-images/site/yt-icons/twitter.jpg"></a>';
    11
      $return .= ' <a href="https://www.facebook.com/sharer/sharer.php?kid_directed_site=0&u=' . urlencode('https://youtu.be/' . $v) . '"><img src="wp-images/site/yt-icons/facebook.jpg"></a>';
    12
      $return .= ' <a href="https://plus.google.com/share?url=' . urlencode('https://youtu.be/' . $v) . '"><img src="wp-images/site/yt-icons/googleplus.jpg"></a>';
    13
      $return .= ' <a href="https://www.blogger.com/blog-this.g?n=' . str_replace(' ', '+', $title) . '&eurl=https://i.ytimg.com/vi/' . $v . '/maxresdefault.jpg&b=%3Ciframe+width%3D%22480%22+height%3D%22270%22+src%3D%22https://www.youtube.com/embed/' . $v . '%22+frameborder%3D%220%22+allowfullscreen%3E%3C/iframe%3E"><img src="wp-images/site/yt-icons/blogger.jpg"></a>';
    14
      $return .= '<input type=text style="width: 200px; font-size: 12pt; height: 25px;" value = "http://youtu.be/' . $v . '" onClick="this.select();">';
    15
     
    16
     return $return;
    17
    }
  • Find other YouTube related posts via our YouTube Tag: youtube tag.
  • See also: "Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)" here. The function returns channel data that'll allow you to return data as follows:

Join 27,900 subscribers that have watched our 111 YouTube videos over 13,339,628 times. Subscribe to our YouTube channel here .

  • Alter all occurrences of images hosted by us to your own website.

Download


Title: Display YouTube Video Data in WordPress (WP Shortcode)
Description: Render YouTube video views, titles, descriptions, likes, dislikes, and other data into your WordPress website or PHP application with shortcode.
  Download • Version 0.2, 2.5K, zip, Category: WordPress Shortcodes
PHP Code & Snippets, (1.4K)    

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Virginia)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment