RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.38% (6.14%*) • Home Loan Fixed: 5.44% (6.26%*) • Fixed: 5.44% (6.26%*) • Variable: 5.38% (6.14%*) • Investment IO: 5.69% (6.52%*) • Investment PI: 5.49% (5.98%*)

Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)

Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)

This is the first of a couple of a few articles that'll deal with obtaining data from YouTube's API (version 3). This post will show you how to use YouTube API to render a viewcount (of total videos), subscriber count, and video count in your WordPress post or page with shortcode, or in a PHP application. A function that'll render data related to a specific video is scheduled in an another article.

Usage of the YouTube API requires an API Key .

In company with our custom text boxes, you can render a result that looks a little like the one below.

Join 0 subscribers that have watched our 0 YouTube videos over 0 times. Subscribe to our YouTube channel here .

WordPress Shortcode Function

We've include two WP shortcode functions; one that utilities the transient API, and other that uses Simple Cache. The former won't return a result if the expiry time has passed and the API can't be reached. Simple Cache, however, will return old data when the API does not respond. We could use a non-expiring option to store the data with the transient to simply record the expiry, but it's added complexity that isn't required.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin. You may optionally download and install our plugin from the bottom of of the page.

1
<?php 
2
/*
3
 Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)
4
 http://www.beliefmedia.com/youtube-channel-data
5
*/
6
 
7
8
 
9
  $atts = shortcode_atts(array(
10
    'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
11
    'channel' => 'UCQq1yfBzyvRFGDs2TjmZTZw',
12
    'n' => 1, /* Number format 1 or 0 */
13
    'type' => 'views', /* views, subscribers, count */
14
    'cache' => '14400'
15
  ), $atts);
16
 
17
 $transient = 'ytcd_' . md5(serialize($atts));
18
 $cached =  get_transient($transient);
19
 
20
 if ($cached !== false ) {
21
 
22
  $type = $atts['type'];
23
  return ($atts['n']) ? number_format($cached["$type"]) : $cached["$type"];
24
 
25
  } else {
26
 
27
   $json_string = @file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&id=' . $atts['channel'] . '&key=' . $atts['apikey']);
28
   if ($json_string !== false) $json = json_decode($json_string, true);
29
 
30
   if ( (is_array($json)) && (count($json) != 0) ) {
31
 
32
        $temp = array();
33
        $temp['views'] = $json['items']['0']['statistics']['viewCount'];
34
        $temp['subscribers'] = $json['items']['0']['statistics']['subscriberCount'];
35
        $temp['count'] = $json['items']['0']['statistics']['videoCount'];
36
 
37
        /* Cache the array */
38
        set_transient($transient, $temp, $atts['cache']);
39
 
40
        /* Return number format result */
41
        $type = $atts['type'];
42
        return ($atts['n']) ? number_format($temp["$type"]) : $temp["$type"];
43
 
44
         } else {
45
 
46
        /* Cache error message for 10 mins */
47
        set_transient($transient, 'Unavailable', '600');
48
        return 'Unavailable';
49
 
50
      }
51
   }
52
}
53
add_shortcode('ytchannel', 'beliefmedia_youtube_channel_data');

The second function utilizes Simple Cache to cache the resulting data array. Use the above function or the one below - not both. Simple Cache may be installed as a standalone plug-and-play plugin.

The shortname name is adjusted for the sake of conflict, but usage is identical. [ytchannel_sc type="views"] will return 0.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin. You may optionally download and install our plugin from the bottom of of the page.

1
<?php 
2
/*
3
 Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)
4
 http://www.beliefmedia.com/youtube-channel-data
5
*/
6
 
7
8
 
9
  $atts = shortcode_atts(array(
10
    'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
11
    'channel' => 'UCQq1yfBzyvRFGDs2TjmZTZw',
12
    'n' => 1, /* Number format 1 or 0 */
13
    'type' => 'views', /* views, subscribers, count */
14
    'cache' => '14400'
15
  ), $atts);
16
 
17
 /* Ensure Simple Cache functions available */
18
 if (!function_exists('beliefmedia_get_transient')) return 'Simple Cache Required';
19
 
20
 $transient = 'yt_channel_data_' . md5(serialize($atts));
21
 $cached =  beliefmedia_get_transient($transient, $atts['cache']);
22
 
23
 if ($cached !== false ) {
24
 
25
  $type = $atts['type'];
26
  return ($atts['n']) ? number_format($cached["$type"]) : $cached["$type"];
27
 
28
  } else {
29
 
30
   $json_string = @file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&id=' . $atts['channel'] . '&key=' . $atts['apikey']);
31
   if ($json_string !== false) $json = json_decode($json_string, true);
32
 
33
   if ( (is_array($json)) && (count($json) != 0) ) {
34
 
35
        $temp = array();
36
        $temp['views'] = $json['items']['0']['statistics']['viewCount'];
37
        $temp['subscribers'] = $json['items']['0']['statistics']['subscriberCount'];
38
        $temp['count'] = $json['items']['0']['statistics']['videoCount'];
39
 
40
        /* Cache the array */
41
        beliefmedia_set_transient($transient, $temp);
42
 
43
        /* Return number format result */
44
        $type = $atts['type'];
45
        return ($atts['n']) ? number_format($temp["$type"]) : $temp["$type"];
46
 
47
         } else {
48
 
49
        /* We'll keep the old data until the API behaves */
50
        $result = beliefmedia_get_transient_data($transient);
51
        return (count($result) != '0') ? number_format($result["$type"]) : 'Unavailable';
52
 
53
      }
54
   }
55
}
56
add_shortcode('ytchannel_sc', 'beliefmedia_youtube_channel_data_sc');

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.

Usage

Shortcode usage is as follows: [ytchannel_sc type="views"] (total video views), [ytchannel_sc type="count"] (total video count), or [ytchannel_sc type="subscribers"] (total subscribers). Available attributes are listed below.

Shortcode Attributes

apikey

The API key is obtained via your Google developer console .

channel

The channel is your channel ID, not your alias. For example, our custom channel URL for FLIGHT is youtube.com/flightorg but our channel URL is https://www.youtube.com/channel/UCQq1yfBzyvRFGDs2TjmZTZw. The latter part of the URL (or everything after channel/) is your ID. You can find your ID by selecting My Channel from YouTube's left hand menu.
Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)

n

n determines whether your results is returned in number format (defaults to true). Alternate notations can be created if desired.

type

The type is either views (total video views), subscribers (total subscribers), or count (total number of videos).

cache

cache determines the length of time the result is cached locally.

PHP Function

The PHP function will query the YouTube API and cache the resulting array locally for a defined period. As such, use of Simple Cache is required.

1
<?php 
2
include('../simple-cache/cache.inc.php');
3
 
4
/*
5
 Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)
6
 http://www.beliefmedia.com/youtube-channel-data
7
*/
8
 
9
function beliefmedia_youtube_channel_data($channel = 'UCuT3w5rdgphV2tYXC4Ki13Q', $type = 'views', $cache = '14400') {
10
 
11
 /* API Key */
12
 $apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
13
 
14
 /* Get transient data */
15
 $transient = 'youtube_channel_data_' . md5(serialize(func_get_args()));
16
 $response = beliefmedia_get_transient($transient, $cache);
17
 
18
 if ($response !== false)  {
19
 
20
   return number_format($response["$type"]);
21
 
22
    } else {
23
 
24
     $json_string = @file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&id=' . $channel . '&key=' . $apikey);
25
     if ($json_string !== false) $json = json_decode($json_string, true);
26
 
27
      if (count($json) != 0) {
28
 
29
        $temp = array();
30
        $temp['views'] = $json['items']['0']['statistics']['viewCount'];
31
        $temp['subscribers'] = $json['items']['0']['statistics']['subscriberCount'];
32
        $temp['count'] = $json['items']['0']['statistics']['videoCount'];
33
 
34
        /* Cache the array */
35
        beliefmedia_set_transient($transient, $temp);
36
 
37
        /* Return number format result */
38
        return number_format($temp["$type"]);
39
 
40
         } else {
41
 
42
        /* We'll keep the old data until the API behaves */
43
        $result = beliefmedia_get_transient_data($transient);
44
        return (count($result) != '0') ? number_format($result["$type"]) : 'Unavailable';
45
 
46
      }
47
   }
48
}

Usage is as follows:

1
/* Get video count */
2
echo beliefmedia_youtube_channel_data('UCQq1yfBzyvRFGDs2TjmZTZw');
3
 
4
/* Get subscriber count */
5
echo beliefmedia_youtube_channel_data('UCQq1yfBzyvRFGDs2TjmZTZw', $type = 'subscribers');
6
 
7
/* Get uploaded video count */
8
echo beliefmedia_youtube_channel_data('UCQq1yfBzyvRFGDs2TjmZTZw', $type = 'count');

WordPress Plugin

If you're using WordPress and prefer the convenience of a plugin, you can download one below. It includes administration options that define the default value to return with [ytchannel]. Any attributes provided in your shortcode will overwrite the defaults.

Retrieve Total YouTube Channel Views, Subscribers, and Video Count (with PHP or WordPress Shortcode)

Upload and activate via your plugins menu. Select Tools -> BeliefMedia YouTube Channel Data to define the defaults (and API key).

Considerations

  • A function (and plugin) to render individual YouTube video stats is scheduled here.

Download


Title: YouTube Channel Views, Subscribers, and Video Count (Shortcode)
Description: Render YouTube video count, channel subscribers, or total video views into WP with shortcode.
  Download • Version 0.2, 1.1K, zip, Category: WordPress Shortcodes
PHP Code & Snippets, (996.0B)    WordPress Plugins (General), (3.4K)    

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment