0

Twitter Stream WordPress Widget

1333570391_flying_bird_sparkles

In a previous article last year I wrote a tutorial about how to Create WordPress Widget To Display Twitter Updates, since then I have learnt a lot more about WordPress development. For this reason I have decided to revisit this widget and make some changes.

When looking back at the code I noticed it was just a mess, I wasn’t inheriting the WP_Widget class, it wasn’t object oriented, it wasn’t nice code. I decided to delete everything on this and start a fresh with a new Twitter stream widget, this time using the WP_Widget class.

In this tutorial we are going to look at how to create a Twitter stream widget in WordPress using the WP_Widget class.

What We Are Going To Create?

This widget is going to display the latest tweets from the given Twitter account. We don’t want to limit the amount of tweets to show this will completely up to the end user of the Widget.

We want the Widget to pick up all links in the Twitter stream and make them clickable on the page.

We want Twitter usernames to be clickable on the page, so if you mention anyone in your Tweets people can click through to their profile straight from your Website.

We also want to display the Twitter follow button on the widget making it easy for your visitors to follow you.

WordPress Widgets

Before we start coding the Widget we need to understand what a WordPress Widget is and how we can use the WordPress Widget API to easily create a WordPress Widgets.

A WordPress widget is a piece of PHP Code which will run inside a WordPress sidebar.

A WordPress sidebar is a registered area in your theme where you can add WordPress Widgets.

WordPress Widgets can easily be added to sidebars by going to the Widget page in the Dashboard and navigate to Appearance -> Widgets. From this Widget page you are able to drag and drop widgets into a sidebar of your choice. The widget should have some sort of Admin form so you can edit the data shown by the widget.

WordPress WP_Widget

To create a WordPress widget all you need to do is inherit from the standard WP_Widget class and use some of it’s functions.

There are 3 main functions that need to be used for the widget to work these functions are form(), widget() and update().

The WP_Widget class is located in wp-includes/widgets.php.

WordPress Starter Widget

Below is the boilerplate of a WordPress widget, when you create a new widget just copy and paste the below code as a starting point for your Widget.

/**
* Adds Foo_Widget widget.
*/
class Foo_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
public function __construct() {
parent::__construct(
‘foo_widget’, // Base ID
‘Foo_Widget’, // Name
array( ‘description’ => __( ‘A Foo Widget’, ‘text_domain’ ), ) // Args
);
}
/**
* Front-end display of widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
extract( $args );
$title = apply_filters( ‘widget_title’, $instance[‘title’] );
echo $before_widget;
if ( ! empty( $title ) )
echo $before_title . $title . $after_title;
?>Hello, World!< ?php echo $after_widget; } /** * Sanitize widget form values as they are saved. * * @see WP_Widget::update() * * @param array $new_instance Values just sent to be saved. * @param array $old_instance Previously saved values from database. * * @return array Updated safe values to be saved. */ public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = strip_tags( $new_instance['title'] ); return $instance; } /** * Back-end widget form. * * @see WP_Widget::form() * * @param array $instance Previously saved values from database. */ public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'New title', 'text_domain' ); } ?>

Widget Function

This Widget function is used to display the Widget on the page.

First we start off by getting the values from the database so we know what information we need to get from Twitter. To get the values from the database we use the second parameter in the widget function.

/* Our variables from the widget settings. */
$this->twitter_title = apply_filters(‘widget_title’, $instance[‘title’] );
$this->twitter_username = $instance[‘username’];
$this->twitter_postcode = $instance[‘postcount’];
$this->twitter_follow_text = $instance[‘tweettext’];

The problem with using the Twitter API is that there is a limit on the amount of requests you get do per hour. This currently stands at 150 requests per hour, so if your website gets more than 150 page views an hour you will need to cache the Twitter results to use in the widget.

WordPress comes with an easy way to store bits of code as a temporary caching, this uses the Transient API by using the get and set transient functions.

Get Transient

The get_transient function will return the cached value for the provided transient name.
< ?php get_transient( $transient_name ); ?>

Set Transient

The set_transient function will set cache in WordPress by supplying the transient name, value to be cached and how long you want it be cached.
< ?php set_transient( $transient_name, $value, $expiration ); ?>

Below is the code we use to cache the tweets from your user stream. This first checks to see if there is anything stored in the cache, if it isn’t then it will call the Twitter API to get the new tweets.
$transName = ‘list-tweets’; // Name of value in database.
$cacheTime = 10; // Time in minutes between updates.
if(false === ($twitterData = get_transient($transName) ) ){
// Get the tweets from Twitter.
$json = wp_remote_get(«http://api.twitter.com/1/statuses/user_timeline.json?screen_name=».$this->twitter_username.»&count=».$this->twitter_postcode);
// Get tweets into an array.
$twitterData = json_decode($json[‘body’], true);
// Save our new transient.
set_transient($transName, $twitterData, 60 * $cacheTime);
}

Now we have the Twitter stream we can display these on the website. We do this by looping through each of the tweets and add them to a list item which we can echo at the end to display all the tweets.

Here is the whole code to display the tweets.

/**
* Front-end display of widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
extract( $args );
/* Our variables from the widget settings. */
$this->twitter_title = apply_filters(‘widget_title’, $instance[‘title’] );
$this->twitter_username = $instance[‘username’];
$this->twitter_postcode = $instance[‘postcount’];
$this->twitter_follow_text = $instance[‘tweettext’];
$transName = ‘list-tweets’; // Name of value in database.
$cacheTime = 10; // Time in minutes between updates.
if(false === ($twitterData = get_transient($transName) ) ){
// Get the tweets from Twitter.
$json = wp_remote_get(«http://api.twitter.com/1/statuses/user_timeline.json?screen_name=».$this->twitter_username.»&count=».$this->twitter_postcode);
// Get tweets into an array.
$twitterData = json_decode($json[‘body’], true);
// Save our new transient.
set_transient($transName, $twitterData, 60 * $cacheTime);
}
/* Before widget (defined by themes). */
echo $before_widget;
?>

< ?php /* After widget (defined by themes). */ echo $after_widget; } /** * Find links and create the hyperlinks */ private function hyperlinks($text) { $text = preg_replace('/\b([a-zA-Z]+:\/\/[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"$1″, $text);
$text = preg_replace(‘/\b(?< !:\/\/)(www\.[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"
$1″, $text);
// match name@address
$text = preg_replace(«/\b([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})\b/i»,»
$1«, $text);
//mach #trendingtopics. Props to Michael Voigt
$text = preg_replace(‘/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)#{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i’, «$1#$2$3 «, $text);
return $text;
}
/**
* Find twitter usernames and link to them
*/
private function twitter_users($text) {
$text = preg_replace(‘/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)@{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i’, «$1@$2$3 «, $text);
return $text;
}
Update Function

The update function is used to add the values of the widget dashboard to the database so we can use this when displaying the Widget.

For this function we are just going to loop through all the inputs from the form and strip all tags from the input boxes. Now we can just return a validated array and these are the values which are added to the database.

/**
* Sanitize widget form values as they are saved.
*
* @see WP_Widget::update()
*
* @param array $new_instance Values just sent to be saved.
* @param array $old_instance Previously saved values from database.
*
* @return array Updated safe values to be saved.
*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
// Strip tags to remove HTML (important for text inputs)
foreach($new_instance as $k => $v){
$instance[$k] = strip_tags($v);
}
return $instance;
}
Form Function

The form function is used on the widgets dashboard screen and will allow you to edit data in the plugin.

From this form we want to change the title of the widget, the Twitter username, the amount of tweets to display and the follow me text.

/**
* Create the form for the Widget admin
*
* @see WP_Widget::form()
*
* @param array $instance Previously saved values from database.
*/
function form( $instance ) {
/* Set up some default widget settings. */
$defaults = array(
‘title’ => $this->twitter_title,
‘username’ => $this->twitter_username,
‘postcount’ => $this->twitter_postcode,
‘tweettext’ => $this->twitter_follow_text,
);
$instance = wp_parse_args( (array) $instance, $defaults ); ?>


get_field_id( ‘postcount’ ); ?>»>< ?php _e('Number of tweets (max 20)', 'framework') ?>
get_field_id( ‘tweettext’ ); ?>»>< ?php _e('Follow Text e.g. Follow me on Twitter', 'framework') ?>


 

Leave a reply