Writing a WordPress Twitter Widget
On the bottom right of the screen you see a live Twitter stream. New tweets that match a given search term are show in real-time. The client script contacts Twitter to get these latest tweet so no server code is running.
This Twitter stream is implemented using a WordPress widget. Widgets are WordPress Plugins that add visual and interactivity options and features, such as sidebar widgets for post categories, tag clouds, navigation, search, etc. Widgets can be added, removed or rearranged via the WordPress Widgets panel and therefore require no code.
Widgets
In this post I will explain how you can implement your own WordPress widget by showing you how I implemented the Twitter widget. The programming languages I used to develop a WordPress widget are PHP and javascript together with some HTML and CSS. I also used the JQuery and JQuery UI libraries for selecting HTML element and animation. PHP is the standard programming language to implement WordPress plugins.
To start with a WordPress plugin you have to create a file with the extension .php. The file name should resemble the name of your plugin. At the top of the file a multi-line comment should be created according to the WordPress plugin format. By using this format WordPress recognizes the file as a WordPress plugin.
/* Plugin Name: Twitter search smooth scrolling Plugin URI: http://www.semanticarchitecture.net/writing-a-wordpress-twitter-widget/ Description: This plug-in shows the most recent tweets that match the search term. Version: 1.0 Author: Patrick Kalkman Author URI: http://www.semanticarchitecture.net/ License: GPL2 */
Notice the fields on each line such as “Plugin Name:” and “Version:”. Only the “Plugin Name” is required, the rest of the fields are optional. It is however good practice to fill the complete header. After this header it is normal to place a reference to the license of your plug-in. Most WordPress plugins use the GPL license.
Widget
The easiest way to create a widget is to subclass WP_Widget. This base class defines the basic skeleton for a WordPress widget.
class Foo_Widget extends WP_Widget {
function __construct() {
parent::WP_Widget();
}
function widget( $args, $instance ) {
}
function update( $new_instance, $old_instance ) {
}
function form( $instance ) {
}
}
The constructor and the four methods are going to be used to implement our widget. Let’s define them one by one.
- Constructor – set the name and description of the widget.
- widget – outputs the HTML content of the widget.
- update – processes the options that should be saved.
- form – outputs the HTML for the options form.
Options
Each WordPress widget can create options. Options are fields that can be filled using the WordPress user interface. These can be use to change the default behavior of your widget.
The Twitter widget has 5 options.
- Title – the title of the widget, shown at the top of the widget.
- Search_query – the string used to filter the tweets.
- refresh_interval – the time to wait until reading new tweets from Twitter.
- tweet_interval – the time to wait before a new Tweet is shown.
- tweet_animation_interval – the duration of the scroll and fade-in effect.
The user interface to let the user enter the values of these options is created in the form method. In this method HTML markup is added to add the form. See the example below which constructs the input field for the Title of the widget.
function form( $instance ) {
$defaults = array('title' => __('Semantic Tweets', WIDGET_NAME));
$instance = wp_parse_args((array)$instance, $defaults);
$title = strip_tags($instance['title']);?>
<p>
<?php _e('Title', WIDGET_NAME) ?>:
<input class="widefat"
name="<?php echo $this->get_field_name('title'); ?>" type="text"
value="<?php echo esc_attr($title); ?>"/>
</p>
<?php
}
A normal input element is used for entering values. The _e() function is used for localization, it uses the ‘Title’ as the key to search for translations in the context of the widget. esc_attr encodes less than, greater than, ampersand, double quote and single quote. The actual value is output via $title. Multiple input fields can be created by copying this row.
Update
The update method is triggered when the user presses the save button in the options screen.
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['search_query'] = strip_tags($new_instance['search_query']);
$instance['refresh_interval'] = strip_tags($new_instance['refresh_interval']);
$instance['tweet_interval'] = strip_tags($new_instance['tweet_interval']);
$instance['tweet_animation_duration'] =
strip_tags($new_instance['tweet_animation_duration']);
return $instance;
}
$new_instance contains the values of the fields that the user entered. By copying those values to the $instance and returning the $instance the values get saved to the WordPress database. The strip_tags is a PHP function that removes the HTML and PHP tags from the given string.
Widget
The widget method creates and displays the actual widget. It output HTML that forms the widget.
function widget($args, $instance) {
echo $before_widget;
echo $before_title . $title . $after_title; ?>
<div class="twitter-search-widget">search-query="<?php echo $search_query; ?>"
refresh-interval="<?php echo $refresh_interval; ?>"
tweet-interval="<?php echo $tweet_interval; ?>"
tweet-animation-duration="<?php echo $tweet_animation_duration; ?>">
</div>
<?php echo $after_widget;
}
The $before_widget and $after_widget are variables that contain markup that can be manipulated by themes. The same goes for $before_title and $after_title. Therefore, to let your widget be theme-able, you should use these variables.
The twitter widget basically is a div with an unordered list, for each new tweet an list item will be created in the unordered list. The list items will be created by javascript.
Registering Javascript
Javascript can be use and is supported by WordPress. Most WordPress version already include JQuery. The proper way to register a JavaScript library is by using the functions wp_register_script and wp_enqueue_script.
function initialize_script() {
wp_register_script('twitter-search-widget',
plugins_url('twitter-search-smooth-scrolling.js',__FILE__ ));
wp_enqueue_script('twitter-search-widget', array('jquery'));
};
With wp_register_script you assign a key to JavaScript file and specify the location of the file. The plugins_url retrieves the url to the plugins directory or to a specific file within that directory. You can hardcode the plugin slug in $path or pass __FILE__ as a second argument to get the correct folder name.
Wp_enqueue_script provides a safe way of adding JavaScript to a WordPress page. Basically, it includes the script if it hasn’t already been included, and load the one that WordPress ships. Note, the second argument that states that the twitter-search-widget JavaScript file is dependent on JQuery. This makes sure that the JQuery library is loaded before this JavaScript file.
Registering CSS
CSS is registered using the same method as with JavaScript. The functions for registering and queueing are called wp_register_style and wp_enqueue_style. Below the actual initialization script of the twitter widget is shown.
function initialize_script() {
wp_register_script('twitter-search-widget',
plugins_url('twitter-search-smooth-scrolling.js',__FILE__ ));
wp_enqueue_script('twitter-search-widget', array('jquery'));
wp_register_style('twitter-search-widget-style',
plugins_url('twitter-search-smooth-scrolling.css',__FILE__ ));
wp_enqueue_style('twitter-search-widget-style');
};
Directory organization
WordPress stores all its plugins in the plug-in folder under wp-content. To be able to install your plugin you need to add the plugin file to the plugin directory. If you have more than one file it is better to create a folder with the same name as the widget and store all files in there.
Source Code
The source code of this plug-in can be found on WordPress.org.


0 Comments
Trackbacks/Pingbacks