Display Vimeo play counts for embedded videos without slowing down your site

Vimeo

Learn how to use Vimeo’s Simple API along with PHP and jQuery to display the play counts of Vimeo videos embedded on your website. This method works asynchronously, meaning that the API calls won’t cause delays in page loading.

Update November 10, 2014

The procedure described below is still an excellent way to use the Simple API to display play counts, but if you wish to display stats for videos which are embedded on your site, yet hidden on Vimeo.com, you will need to use the new Vimeo API. Peruse the comments section at the bottom of the page for some tips on how to adjust your code for the new API.

» Scroll to step-by-step instructions

Vimeo play count with jQuery

Let me start by saying that I’m a fan of Vimeo. For years I hosted and served all my videos from my own server because I was not aware of any service that offered the kind of reliability, quality, and fine-tuned control that I require. Vimeo’s emergence changed that. I joined Vimeo about a year ago, immediately upgraded to Vimeo Plus, and now host most of my videos with them for this website and personal use.

The benefits of Vimeo over other services are numerous, but to name one of the most crucial, they allow you to update a video file without losing your metadata, stats, and comments. It would be hard to overstate how huge this is. If you’ve ever made an adjustment to a video that you posted on a service that doesn’t allow this, you know how frustrating it is to have to decide between starting over or accepting that viewers aren’t going to see the latest and greatest version of your video.

Another example of Vimeo’s versatility is their API, which brings us to the topic at hand. The below tutorial will walk you through a straightforward way to display the number of views that your Vimeo videos have received.

You can download the scripts and a sample html file here: vimeo-stats-dax-v1.2.zip.

To see a demonstration of this method in action, take a look at the Packafoma Video Production page. Note that the Vimeo “plays” pop onto the screen a moment after the document loads, never holding up the loading of the other elements of the page.

If you have questions or suggestions on how these scripts could be improved, please share in the discussion.

Step-by-step tutorial:

1 Create the following PHP script and save it as vimeo-stats-dax.php. (I would suggest creating a new directory specifically for these scripts. I’ve used “vsd-scripts” in the examples.)

This function uses the Vimeo API to retrieve information about a video using its ID number and turns it into a form we can use:

<?php
function getVimeoStats($id) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "http://vimeo.com/api/v2/video/$id.php");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	$output = unserialize(curl_exec($ch));
	$output = $output[0];
	curl_close($ch);
	return $output;
}
?>

Now, at this point, you could display the play count for any video simply by adding the above script to the <head> of your HTML/PHP page and then adding the following code to the body of the same page exactly where you would like the data to appear (replacing 12345678 with the Vimeo ID number of your video).

This code snippet is provided as an example of a simple way to add the play count, but skip it if you are interested in the more advanced, asynchronous method that follows.

<?php // THIS TECHNIQUE WORKS, BUT IT'S NOT RECOMMENDED
	$VimeoStats = getVimeoStats(12345678); // set video ID
	$plays = $VimeoStats['stats_number_of_plays'];
	echo $plays;
?>

If you are loading the play count for only one video and the count is displayed late in the document flow, the above may very well meet your needs. If that’s the case, congratulations! You have everything you need.

However, this simple method has a drawback. When the browser reaches the above command, it will stop loading the rest of the page until the response data has been received. This sometimes takes several seconds and can prevent the entire page from loading depending on the placement of the code in the document. This becomes severely problematic when retrieving play counts for multiple videos on the same page.

So we soldier on…

2 Create the following PHP script for each video for which you would like to display the play count. Save the file as vsd.12345678.php, replacing 12345678 with the ID of your video. (The filename does not have to contain this number. For instance, you may prefer to add the title of the video, but I find that using IDs helps with the configuration of the next steps.)

In the script itself, replace 12345678 with the Vimeo ID number of your video and set the proper path to your vimeo-stats-dax.php file. You will need to create a separate file for each video, although you can start with just one.

This script uses the script we created in step 1 to retrieve and display the play count of a specified video:

<?php // you can note the title of the video in this comment
require($_SERVER['DOCUMENT_ROOT']."/vsd-scripts/vimeo-stats-dax.php"); // path to vimeo-stats-dax.php

$VimeoStats = getVimeoStats(12345678); // set video ID
	$plays = $VimeoStats['stats_number_of_plays'];
	$likes = $VimeoStats['stats_number_of_likes'];
	$comments = $VimeoStats['stats_number_of_comments'];

echo $plays;
?>

Notice that I’ve included several response data variables as examples, although only the play count is being outputted.

3 Place the following in the <head> section of the HTML/PHP page that contains your video (or any page for that matter). Replace 12345678 with the video ID (same ID in both spots) and edit the path to the vsd.12345678.php file you just created. Note the pound (#) symbol in front of the first video ID. If you are displaying multiple videos on the same page, simply duplicate this line, adjusting the ID numbers for each video.

This jQuery script waits for the web page to finish loading and then runs the above PHP script to find the play count(s). It then inserts the results into the web page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
	$('#12345678').load('/vsd-scripts/vsd.12345678.php'); // set video ID; duplicate this line for multiple videos and note the title of each video in this comment
});
</script>

4 Now for the easy part: the HTML. All you have to do is add the following snippet to your same web page with the proper video ID wherever you would like the play count for that video to appear. Feel free to add CSS classes to the span if you wish to format the data.

<span id="12345678"></span>

That’s it. Now you can display Vimeo views without hurting your PageSpeed.

Discussion

9 comments on “Display Vimeo play counts for embedded videos without slowing down your site”
  1. Matt  

    Works great. Thanks!

  2. Jonathan  

    Excellent thank you!

  3. Sonicx2218  

    I got stuck with Wix for a client, and the only form of code they offer is pasting html in an Iframe. They don’t support PHP directly, but they said host the php on another server and embed the code in iframe. Is it even possible to achieve this tutorial in some way on there?

    • Dax  

      Unfortunately, I think it would be very difficult to implement the system outlined in this tutorial given those limitations. Theoretically, you could run all the code off of another server and embed the results in an iFrame as they suggested, but it wouldn’t be a very practical solution.

  4. code natives  

    Nice work. Thank you for sharing.

  5. Ahmad Ahdab  

    Great code, thanks a lot. I have a small question if you please, this code works very well on public videos on Vimeo. In my case, as a pro user, I made some of my videos private so that they can only be accessed from my website and not from Vimeo. I would like to display the plays stats on my website but when using this code the function curl_exec($ch) is returning video not found. How can I access my private video stats to display them on my website?

    • Dax  

      You’re welcome! Unfortunately, Vimeo’s Simple API cannot be used to access data from private videos. This is what their help doc has to say:

      The Simple API is for public data only. If your videos are private, you will need to use the Advanced API. If your video is set to hide from vimeo.com, but is embeddable, you may also be able to use oEmbed.

      The Advanced API mentioned in that statement is actually deprecated now, but I would look into the new Vimeo API.

    • Ahmad Ahdab  

      Thanks again, I figured it out but I struggled a bit, so I thought in sharing my solution in case anyone is interested.

      (1) Create an app on Vimeo and get the Client Identifier, Client Secret, and generate an Access Token with the properties Public Private Interact.

      (2) Download from Vimeo the PHP source code.

      (3) Strangely, at least in my case, the code had a wrong syntax on line 473 in the statement $name = array_slice(explode(“/”, $file_path), -1)[0]; to solve it remove the [0] at the end! In fact I didn’t need to call this function to know if it did any harm.

      (4) More strangely, the PHP code provided by Vimeo can not do authentication with their new system so you need to add this code curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); before every $response = curl_exec($curl); statement. This should be 3 additions.

      (5) Finally, create your own PHP script, here is mine:

      require("../Vimeo PHP path/autoload.php");
      use VimeoVimeo;
      $client_id = "*****"; //your Vimeo number here
      $client_secret = "*****"; //your Vimeo number here
      $access_token = "*****"; //your Vimeo number here
      
      $vim = new Vimeo($client_id, $client_secret, $access_token);
      $response = $vim->request("/videos/****"); //your Vimeo PRIVATE video ID here
      echo $response["body"]["stats"]["plays"];

      Again thanks a lot for your original post, sorry if I bothered but I struggled to get this and I thought someone might be interested to know my solution.

    • Dax  

      Awesome. Thanks for sharing!

      I’ve actually rewritten the scripts I use here on packafoma.com to utilize the new API. I figure it’s less likely to be deprecated, and it works with embedded videos that are hidden on vimeo.com.

      Your fix for the syntax error in line 471 of Vimeo.php was crucial! However, I did not find I needed to make any adjustments to the $response = curl_exec($curl) statements. Maybe they fixed it.

      My retrieval script looks like this:

      <?php
      require($_SERVER['DOCUMENT_ROOT'].'/LOCAL_PATH/vimeo.php-master/autoload.php'); // set your local path
      use Vimeo\Vimeo;
      function getVimeoStats($vimeoID) {
      	$clientID = '12345678'; // your client ID
      	$clientSecret = '12345678'; // your client secret
      	$accessToken = '12345678'; // your access token
      	$authentication = new Vimeo($clientID, $clientSecret, $accessToken);
      	$response = $authentication->request('/videos/'.$vimeoID);
      	return $response;
      }
      ?>
      
Post a comment…

Your email address will never be published or shared.

You may use these HTML tags: <a href=""> <strong> <em>   |   For code samples, please wrap between [code] and [/code]

Email me when someone replies:

Dax Roggio Instagram Dax Roggio tweets Dax Roggio videos Dax Roggio photos Packafoma newsletter