Problem
How to create and display items that use/embed YouTube videos.
Solution
The key is to include the YouTube video's unique identifier when adding metadata to an item. The YouTube identifier is part of a video's url. For example:
- YouTube video url: http://www.youtube.com/watch?v=R8XAlSp838Y
- YouTube identifier: R8XAlSp838Y
The YouTube identifier is necessary for creating video embed code, and/or obtaining YouTube-provided thumbnail image URLs. For the purpose of this recipe, the YouTube identifier will reside in an item's Dublin Core "Identifier" field.
The general strategy is to first use the item() function to retrieve the YouTube identifier, and then use the identifier to create the embed code or thumbnail image path URL for display.
Functions Used
Here's an example of how to display YouTube video within a page, such as the item view page (applications/views/scripts/items/show.php)
<?php /* First get the YouTube identifier from the item metadata: */ ?> <?php $youtube_id= item('Dublin Core', 'Identifier');?> <!--Now create the embed code at the point you want to display the video --> <iframe width="784" height="588" src="http://www.youtube.com/embed/<?php echo $youtube_id;?>" frameborder="0" allowfullscreen></iframe>
To see what options are available to construct the YouTube embed code, check out the documentation.
To display standard YouTube thumbnail images, a similar technique is used. Here is some code that could be used on the browse items page (applications/views/scripts/items/browse.php):
<?php /*loop through items: */ ?> <?php while (loop_items()): ?> <?php /* retrieve the YouTube identifier from the metadata */?> <?php $youtube_id= item('Dublin Core', 'Identifier'); ?> <?php /* create the YouTube standard URL element */?> <?php $youtube_thumb="<img src='http://img.youtube.com/vi/$youtube_id/hqdefault.jpg'>"; ?> <?php /* use "link_to_item" to display the clickable thumbnail, linked to its item view page */ ?> <?php echo link_to_item($youtube_thumb); ?> <?php /* include the item's title */ ?> <h2><?php echo link_to_item(item('Dublin Core', 'Title'), array('class'=>'permalink')); ?></h2> <?php endwhile; ?>