The purpose of this tutori al is to create a widget that will show the latest videos from a particular Youtube user. For this tutorial we will use some JQuery magic and the power of Youtube GDATA Api.
The Widget structure
WordPress Widgets (WPW) is like a plugin, but designed to provide a simple way to arrange the various elements of your sidebar content (known as “widgets”) without having to change any code.
Here we have the structure of the widget (the widget class), each method is commented so you can understand what it means.
/* YOUTUBE WIDGET */
class YT_Channel_Latest_Videos extends WP_Widget {
// the widget constructor
function YT_Channel_Latest_Videos() {
parent::WP_Widget(false, $name = 'Youtube latest videos');
parent::__construct(__CLASS__, 'Youtube latest videos', array(
'classname' => __CLASS__,
'description' => "This widget will show the latest videos from a youtube user."
));
}
// content of the widget - front-end
function widget($args, $instance) {
}
// get the options
function update($new_instance, $old_instance) {
}
// the form that shows in your administration area - here you insert the widget options
function form($instance) {
}
}
// register the widget
add_action('widgets_init', create_function('', 'register_widget("YT_Channel_Latest_Videos");'));
We will take it step by step, first we need to create the interface that will show up in the admin area, there you must be able to enter some options and save them in the database.
// the form that shows in your administration area - here you insert the widget options
function form($instance) {
$title = esc_attr($instance['title']);
$channel = esc_attr($instance['channel']);
$nr_videos = esc_attr($instance['nr_videos']);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">Title:</label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('channel'); ?>">Youtube channel:</label>
<input class="widefat" id="<?php echo $this->get_field_id('channel'); ?>" name="<?php echo $this->get_field_name('channel'); ?>" type="text" value="<?php echo $channel; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('nr_videos'); ?>">Number of videos to show:</label>
<input size="3" id="<?php echo $this->get_field_id('nr_videos'); ?>" name="<?php echo $this->get_field_name('nr_videos'); ?>" type="text" value="<?php echo $nr_videos; ?>" />
</p>
<?php
}
Update the options:
// get the options
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['channel'] = strip_tags($new_instance['channel']);
$instance['nr_videos'] = strip_tags($new_instance['nr_videos']);
return $instance;
}
Next we extract the latest videos from a given user using the power of jQuery (the javascript code is commented):
// content of the widget - front-end
function widget($args, $instance) {
remove_action("wp_print_footer_scripts", array(__CLASS__, 'remove_enqueued_script'));
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
?>
<?php echo $before_widget; ?>
<?php if ( $title )
echo $before_title . $title . $after_title; ?>
<script type="text/javascript">
// avoid conflicts with other libraries
jQuery.noConflict();
(function($) {
$(function() {
var yt_subscription_url = 'http://gdata.youtube.com/feeds/api/users/<?php echo $instance['channel']; ?>/uploads?max-results=<?php echo $instance['nr_videos']; ?>&alt=json';
// the div element where we build the videos list
$target_element = $('#recentUserVideosYoutube');
// make an ajax request to get the videos from youtube
$.ajax({
url: yt_subscription_url,
data_type: 'json',
success: function(response){
if( response != "" && response != undefined ) {
// parse json object
var jsonObject = $.parseJSON(response);
var html_build = '<div>';
// loop through each video
$.each(jsonObject.feed.entry,function(i,video){
// video link
var link = video.link[0].href;
// thumbnail
var image_url = video.media$group.media$thumbnail[1].url;
var image_width = video.media$group.media$thumbnail[1].width;
var image_height = video.media$group.media$thumbnail[1].height;
//title
var title = video.media$group.media$title.$t;
// description
var description = video.media$group.media$description.$t;
// duration in seconds
var duration = video.media$group.yt$duration.seconds;
// view count
var views = video.yt$statistics.viewCount;
// start building the html for this video
html_build += '<div style="float: left; width: '+(parseInt(image_width))+'px; height: '+(parseInt(image_height))+'px; margin-bottom:5px;">';
html_build += '<a href="'+link+'" target="_blank" title="'+title+'"><img src="'+image_url+'" alt="'+title+'" width="'+image_width+'" height="'+image_height+'" border="0" /></a>';
html_build += '</div>';
html_build += '<div style="clear: left"></div>';
});
// close div
html_build += '</div>';
// empty the div
$target_element.empty();
// put the html code
$target_element.html( html_build );
} else {
// empty the div
$target_element.empty();
// put the html code
$target_element.html( '<p>No videos, yet...</p>' );
}
},
error: function() {
// empty the div
$target_element.empty();
// put the html code
$target_element.html( '<p>No videos, yet...</p>' );
}
});
});
})(jQuery);
</script>
<div id="recentUserVideosYoutube">
<p>Loading results...</p>
</div>
<?php echo $after_widget; ?>
<?php
}
The widget code is ready, now we need to pack it in a plug
WordPress Plugin: A WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog, which can be seamlessly integrated with the weblog using access points and methods provided by the WordPress Plugin Application Program Interface (API).
For the plugin is easy, in the plugins directory create a file named latest-youtube-videos-widget.php and the following piece of code in the header of the file:
<?php
/*
Plugin Name: Latest Youtube Videos Widget
Plugin URI: http://blog.creative-webdesign.info
Description: Show the latest youtube videos uploaded by a user.
Version: 1.0
Author: Alex Raduta
Author URI: http://blog.creative-webdesign.info
*/
Show the latest videos from a youtube channel with Youtube GDATA Api – WordPress widget
The purpose of this tutori al is to create a widget that will show the latest videos from a particular Youtube user. For this tutorial we will use some JQuery magic and the power of Youtube GDATA Api.
The Widget structure
Here we have the structure of the widget (the widget class), each method is commented so you can understand what it means.
/* YOUTUBE WIDGET */ class YT_Channel_Latest_Videos extends WP_Widget { // the widget constructor function YT_Channel_Latest_Videos() { parent::WP_Widget(false, $name = 'Youtube latest videos'); parent::__construct(__CLASS__, 'Youtube latest videos', array( 'classname' => __CLASS__, 'description' => "This widget will show the latest videos from a youtube user." )); } // content of the widget - front-end function widget($args, $instance) { } // get the options function update($new_instance, $old_instance) { } // the form that shows in your administration area - here you insert the widget options function form($instance) { } } // register the widget add_action('widgets_init', create_function('', 'register_widget("YT_Channel_Latest_Videos");'));We will take it step by step, first we need to create the interface that will show up in the admin area, there you must be able to enter some options and save them in the database.
// the form that shows in your administration area - here you insert the widget options function form($instance) { $title = esc_attr($instance['title']); $channel = esc_attr($instance['channel']); $nr_videos = esc_attr($instance['nr_videos']); ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>">Title:</label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('channel'); ?>">Youtube channel:</label> <input class="widefat" id="<?php echo $this->get_field_id('channel'); ?>" name="<?php echo $this->get_field_name('channel'); ?>" type="text" value="<?php echo $channel; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('nr_videos'); ?>">Number of videos to show:</label> <input size="3" id="<?php echo $this->get_field_id('nr_videos'); ?>" name="<?php echo $this->get_field_name('nr_videos'); ?>" type="text" value="<?php echo $nr_videos; ?>" /> </p> <?php }Update the options:
// get the options function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); $instance['channel'] = strip_tags($new_instance['channel']); $instance['nr_videos'] = strip_tags($new_instance['nr_videos']); return $instance; }Next we extract the latest videos from a given user using the power of jQuery (the javascript code is commented):
// content of the widget - front-end function widget($args, $instance) { remove_action("wp_print_footer_scripts", array(__CLASS__, 'remove_enqueued_script')); extract( $args ); $title = apply_filters('widget_title', $instance['title']); ?> <?php echo $before_widget; ?> <?php if ( $title ) echo $before_title . $title . $after_title; ?> <script type="text/javascript"> // avoid conflicts with other libraries jQuery.noConflict(); (function($) { $(function() { var yt_subscription_url = 'http://gdata.youtube.com/feeds/api/users/<?php echo $instance['channel']; ?>/uploads?max-results=<?php echo $instance['nr_videos']; ?>&alt=json'; // the div element where we build the videos list $target_element = $('#recentUserVideosYoutube'); // make an ajax request to get the videos from youtube $.ajax({ url: yt_subscription_url, data_type: 'json', success: function(response){ if( response != "" && response != undefined ) { // parse json object var jsonObject = $.parseJSON(response); var html_build = '<div>'; // loop through each video $.each(jsonObject.feed.entry,function(i,video){ // video link var link = video.link[0].href; // thumbnail var image_url = video.media$group.media$thumbnail[1].url; var image_width = video.media$group.media$thumbnail[1].width; var image_height = video.media$group.media$thumbnail[1].height; //title var title = video.media$group.media$title.$t; // description var description = video.media$group.media$description.$t; // duration in seconds var duration = video.media$group.yt$duration.seconds; // view count var views = video.yt$statistics.viewCount; // start building the html for this video html_build += '<div style="float: left; width: '+(parseInt(image_width))+'px; height: '+(parseInt(image_height))+'px; margin-bottom:5px;">'; html_build += '<a href="'+link+'" target="_blank" title="'+title+'"><img src="'+image_url+'" alt="'+title+'" width="'+image_width+'" height="'+image_height+'" border="0" /></a>'; html_build += '</div>'; html_build += '<div style="clear: left"></div>'; }); // close div html_build += '</div>'; // empty the div $target_element.empty(); // put the html code $target_element.html( html_build ); } else { // empty the div $target_element.empty(); // put the html code $target_element.html( '<p>No videos, yet...</p>' ); } }, error: function() { // empty the div $target_element.empty(); // put the html code $target_element.html( '<p>No videos, yet...</p>' ); } }); }); })(jQuery); </script> <div id="recentUserVideosYoutube"> <p>Loading results...</p> </div> <?php echo $after_widget; ?> <?php }The widget code is ready, now we need to pack it in a plug
in so it can be released to the public.
Packing it in a plugin
For the plugin is easy, in the plugins directory create a file named latest-youtube-videos-widget.php and the following piece of code in the header of the file:
Then copy the widget code and its done.
You can download the final plugin file from here: latest-youtube-videos-widget.zip