There are plenty of YouTube plugins in the WordPress.org plugin repository, and even in the Envato marketplace, but sometimes a plugin is just overkill for a very simple implementation of recent videos fetched from an RSS feed.
In this tutorial, we'll go over how to use data returned from fetch_feed()
to output a YouTube video page template.
Creating a Page Template
The finished code could also very easily be made into a reusable function, but since we're dealing with the topic of theme development, we're going to wrap this into a page template.
The best way to get started is to simply duplicate the theme's page.php template if it exists, or start with the theme's single.php. The key things you'll want to make sure the file has are the template name, and calls to get_header()
and get_footer()
. To provide the template name, you'll simply add it to the top of the document in comments like so:
<?php /** * Template Name: Piano Cat Videos Page */ ?>
This will create a new option in the page attributes template field to select the custom page template which should look similar to the figure here.
Turn an RSS Feed Into Usable Data With fetch_feed()
WordPress provides us a nice little way to turn an RSS feed into an object that can be used to loop through items and return other data. This is done with the fetch_feed()
function. To begin using this function, we'll set up a few parameters and a couple of error conditionals with the next snippet of code.
<?php $uri = 'http://gdata.youtube.com/feeds/api/videos?alt=rss&q=piano cat'; $feed = fetch_feed( $uri ); if ( is_wp_error( $feed ) ) { return false; } else { $maxitems = $feed->get_item_quantity( 10 ); $rss_items = $feed->get_items( 0, $maxitems ); if ( $maxitems == 0 ) : return false; else : if ( is_array( $rss_items ) ) : ?> ... do stuff ... <?php endif; endif; } ?>
Firstly, we need to set our RSS feed URL. If you have trouble finding the RSS feed that you want, you can try using Google's YouTube API feed generator. Be careful to make sure you set each parameter carefully because not all RSS feed URL's will return the desired results. The default settings should work and I advise using the search query and RSS 2.0 output too for best results.
Once you have your URL, turn it into an object variable with the magical fetch_feed()
function. Then run it through a check to make sure there aren't any errors and look for items to be returned. If you're a power user, you might be entertained by doing a var_dump( $feed )
to see everything the object has to offer.
Now that we have our foundation set, our page should be rendering "... do stuff ..." because there is a return for the feed. Now we can start getting ready to output the videos that the feed returns.
Laying the Video Output Foundation
Before we get too far ahead of ourselves, let's go ahead and lay down some markup and styling. For this layout, we'll have a large video player iframe
on the top of the page and then thumbnails of each video in a two column list below. Let's replace our "do stuff" placeholder with this:
<div id="videos"> <div class="video_player"> <iframe width="610" height="344" src="http://www.youtube.com/embed/VIDEO_ID" frameborder="0" allowfullscreen></iframe> </div> <ul class="video_thumbs"> <li> <p><a href="http://www.youtube.com/embed/VIDEO_ID"><img src="youtube/image.jpg" width="290" height="164" /></a></p> <p><a href="http://www.youtube.com/embed/VIDEO_ID">Video Title</a></p> </li> </ul> </div>
Inside our containing div, we have two main elements. The first one is for the large video player and will contain the actual working video embed; the other is a list for the video selection columns with thumbnails and video titles. Next, we'll style that up by dropping some CSS in the theme's stylesheet.
#videos { width: 640px; } .video_player { padding: 15px; } .video_thumbs { margin: 0; } .video_thumbs li { list-style: none; padding: 15px; margin: 0; float: left; width: 290px; } .video_thumbs p { margin: 10px 0; } .video_thumbs li:hover img, .video_thumbs li.active img { opacity: .5; }
This CSS sets the video_player
up to have some space around it and creates two equal columns below it.
Getting the Video ID
There's one more step before we begin parsing the data that we've fetched from the RSS feed. We're going to need to find the video ID in each video item.
To do that, we'll create a separate function that we'll place in the theme's functions.php file so that it's ready for us to use in the template.
function wptuts_get_yt_ID( $uri ) { // how long YT ID's are $id_len = 11; // where to start looking $id_begin = strpos( $uri, '?v=' ); // if the id isn't at the beginning of the uri for some reason if( $id_begin === FALSE ) $id_begin = strpos( $uri, "&v=" ); // all else fails if( $id_begin === FALSE ) wp_die( 'YouTube video ID not found. Please double-check your URL.' ); // now go to the proper start $id_begin +=3; // get the ID $yt_ID = substr( $uri, $id_begin, $id_len); return $yt_ID; }
This bit of code basically searches a provided URL for an 11 character string that follows "&v=
" in the query and strips off those first three characters to produce the video's ID. We can use this to replace "VIDEO_ID
" in our markup.
The Moving Pieces: Outputting the Videos and Thumbnails
Now we can use our markup and replace our plain markup with some working code like so:
<div id="videos"> <div class="video_player"> <?php $i = 0; foreach ( $rss_items as $item ) : if ( $i++ > 0 ) break; $id = wptuts_get_yt_ID( $item->get_permalink() ); ?> <iframe width="610" height="344" src="http://www.youtube.com/embed/<?php echo $id; ?>" frameborder="0" allowfullscreen></iframe> <?php endforeach; ?> </div> <ul class="video_thumbs"> <?php foreach ( $rss_items as $item ) : $id = wptuts_get_yt_ID( $item->get_permalink() ); $enclosure = $item->get_enclosure(); ?> <li> <p><a href="http://www.youtube.com/embed/<?php echo $id; ?>"><img src="<?php echo esc_url( $enclosure->get_thumbnail() ); ?>" width="290" height="164" /></a></p> <p><a href="http://www.youtube.com/embed/<?php echo $id; ?>"><?php esc_html_e( $item->get_title() ); ?></a></p> </li> <?php endforeach; ?> </ul> </div>
This creates two loops through the RSS items. The first will break after the first item since we only want to return one iframe
to start out with.
The second loop gets the $id
and $enclosure
of each item using the SimplePie functions available to us and outputs the proper thumbnail URL and title, linked to the embed URL for each photo.
Making the Thumbnail Links Work
The final step is to drop in some jQuery that will cancel out the default behaviour of each thumbnail link and instead use those URL's to change the embedded video in the iframe
. To do this, enqueue a custom JavaScript file from your functions.php like so:
add_action( 'wp_enqueue_scripts', 'wptuts_enqueue_video_js' ); function wptuts_enqueue_video_js() { if ( is_page_template( 'page-cats.php' ) ) wp_enqueue_script( 'video_js', get_template_directory_uri() . '/js/video.js', array( 'jquery' ) ); }
This code will check to make sure we're on the custom page template named "page-cats.php" so that we only call the script on that page and then enqueue a JS file that it will look for in our theme's "js" directory and require jQuery to run it. Now you can create that JavaScript file with the following code in it:
jQuery( function($) { $( '#videos .video_thumbs li:first-child' ).addClass( 'active' ); $( '#videos .video_thumbs a' ).on( 'click', function(e) { e.preventDefault(); $( '#videos .video_thumbs li' ).removeClass( 'active' ); $( this ).parentsUntil( 'ul' ).addClass( 'active' ); var video = $( this ).attr( 'href' ); $( '#videos .video_player iframe' ).attr( 'src', video ); }); });
This code will add the "active
" class to the first video thumbnail li
. Then when a thumbnail link is clicked it will stop the link from leaving the page, add the "active
" class to the clicked on item, and use the URL from the link to replace the URL in the iframe
source, thus replacing the active video with the new one.
Conclusion
As a result of all your hard work, you should have a custom video page that looks something like this:
Comments