Paulund
2012-07-27 #wordpress

Create Favourite Tweets WordPress Dashboard Widget

Twitter is a great tool to quickly network with people that have similar interests as you. If your a blogger it is also a get place to get ideas for your next blog post, when you find a tweet that is interesting to you and you want to save it Twitter has made a feature to favourite tweets.

When you favourite a tweet it gets added to your favourite list making it really easy for you to come back at a later date and find that tweet again. If you are using this to keep track of your next blog post ideas then it would be a good idea to have a nice place in Wordpress to see all your favourite tweets. When you have a Wordpress blog you tend to spend most of your time online logged into Wordpress trying to improve your site. Why not have a dashboard widget which displays all your favourite tweets that way when you log into Wordpress you will be presented with a list of your favourites to get inspiration for your next post. In this tutorial I will show you how to easily create a Wordpress dashboard widget to display your favourite tweets.

Dashboard Widgets

Wordpress main page when you log in to the admin area is the dashboard page this has a number of different widgets that give you an overall status of your blog. You can see posts, pages, comments, spam, drafts and Wordpress news. The dashboard is the place where you will see messages to upgrade Wordpress when they come up with new versions. You can also change this to display your own important message on the dashboard. Urgent Messages In WordPress Dashboard. With all the widgets you can expand or collapse the content or drag and drop them to be displayed anywhere on the page. If you don't want some of the default dashboard widgets on the screen you can remove them with this snippet, just add this to the functions.php file.


function disable_dashboard_widgets() {  
    remove_meta_box('dashboard_right_now', 'dashboard', 'core');
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'core');
    remove_meta_box('dashboard_incoming_links', 'dashboard', 'core');
    remove_meta_box('dashboard_plugins', 'dashboard', 'core');
    remove_meta_box('dashboard_quick_press', 'dashboard', 'core');
    remove_meta_box('dashboard_recent_drafts', 'dashboard', 'core');
}
add_action('admin_menu', 'disable_dashboard_widgets');

But you can also use this in-built Wordpress function to customise this area as much you want all you have to do to create a new Wordpress dashboard widget is use the function wp_add_dashboard_widget().


<?php 
wp_add_dashboard_widget($widget_id, $widget_name, $callback, $control_callback );
?>

Setup The Plugin

We are going to create a Wordpress plugin that will create a new dashboard widget and display the favourite tweets for any Twitter user. First we need to create the folder structure for your widget. Create a new folder in the wp-content/plugins folder called paulund-favourite-tweets-widget. Then create a new php file and at the top of the file place the following comments.


<?php
/*
Plugin Name: Paulund Favourite Tweets Widget
Plugin URI: http://www.paulund.co.uk
Description: Creates a dashboard widget to display your favourite tweets
Version: 1.0
Author: Paulund
Author URI: http://www.paulund.co.uk
*/
?>

Create a new class to run and make sure we run this class only on the admin screen.


// Only display the Fav tweet if on the admin page
if(is_admin()){
	new Paulund_Fav_Tweets_Dashboard_Widget();
}

/**
* Paulund Fav tweets dashboard widget
* This uses the tweet api to get the favourite tweets for a certain user and displays it on the dashboard
*/
class Paulund_Fav_Tweets_Dashboard_Widget
{
        /**
	* Default user to get favourites
	*/
	private $username = "paulund_";

	/**
	* Number of favourite tweets
	*/
	private $limit_tweets = 10;

}

As you can see there are two variable defined at the top of the class $username and $limit_tweets. If you want to display user own tweets then change the username to your own Twitter account name. With the plugin setup now we can start creating the functionality for the widget.

Constructor

In the constructor of the class we are going to define an action to run a class which creates a new widget and adds style to the page.


/**
* Constructor to the Fav tweets dashboard widget
* This will setup the widget and display the tweets
*/
public function __construct(){
	add_action( 'wp_dashboard_setup', array(&$this, 'Favs_Dashboard_Setup' ));
        add_action( 'admin_enqueue_scripts', array(&$this, 'load_styles'));
}

public function load_styles()
{
	wp_enqueue_style('fav-tweets', plugins_url( '/paulund-favourite-tweets-widget/css/pu-fav-tweets.css' ));
}

This runs a function Favs_Dashboard_Setup when Wordpress will try to setup the dashboard widget, so we need to create the Favs_Dashboard_Setup function to create our favourite tweet widget.

Setup The Dashboard

On the wp_dashboard_setup action Wordpress will create all the defined widgets, this is the point we are going to run our function Favs_Dashboard_Setup. In this function we are going to create our widget by using the Wordpress function wp_add_dashboard_widget().


/**
* Setup the dashboard favourites
*/
public function Favs_Dashboard_Setup(){
     wp_add_dashboard_widget(
            'fav-tweets-dashboard-widget',
            'Favourite Tweets',
            array(&$this, 'Fav_Tweets_Dashboard_Content'),
            $control_callback = null
	     );
}

The third parameter of this function is the callback function which is ran to display the content inside the widget, using a function called Fav_Tweets_Dashboard_Content. ## Displaying The Content

When the widget gets created we need to create another function to run which adds the content inside the widget. Within this function we are going to get the Tweets from the Twitter API and then display then nicely on the widget.


/**
* Get the content of the favourite tweets and displays the on the dashboard
*/
public function Fav_Tweets_Dashboard_Content(){
	$tweets_array = $this->Get_Fav_tweets($this->username, $this->limit_tweets);
	if($tweets_array != false){
		foreach($tweets_array as $tweets)
		{
			$this->Display_Tweets($tweets->user->screen_name, 
						$tweets->user->profile_image_url_https, 
						$tweets->text, 
						$tweets->created_at);
		}
	}
}

This function starts off by getting all the favourite tweets passing in the username and the limit of tweets which is defined at the top of the class. This function returns an array of tweets so that we can loop through all of these and pass in the required information to the display tweets function. The parameters we are going to pass in to be displayed is the username, user image, tweet text and the date the tweet was created.

Get Favourite Tweets From Twitter API

This is where we are going to create the function to get the favourite tweets from the twitter API. In this function we are going to pass in 2 parameters a username to get the favourites and a limit on the amount of the tweets we want to get back. When we have these parameters we can construct a URL to access the favourites from the twitter API. Once we have the URL for the tweets we can use the Wordpress function wp_remote_get() to get the contents of the URL, which is returned in JSON format and added to the returned variable. With this JSON string we can then turn this into an array by using the PHP function json_decode() and pass in the JSON string, when we have this array it can be returned so we can loop through them to display each tweet correctly.


/**
* Get the fav tweets uses the wordpress remote get function
*
* @param $username - User to get fav tweets
* @param $limit - Limit number of fav tweets
*
* @return An array of the favourite tweets
*/
private function Get_Fav_tweets($username, $limit){
	$tweets = wp_remote_get('https://api.twitter.com/1/favorites.json?count='.$limit.'&screen_name=' .$username);

	if($tweets['response']['code'] == 200 && !empty($tweets['body'])){
		return json_decode($tweets['body']);
	}

	return false;
}

Display The Tweets

Then we can create the function to display the tweets on the screen all we are going to do for this is echo a div displaying the username, an image, the tweet and the date of the tweet.


/**
* Display the tweets on the widget
*
* @param $user - Username of the tweet
* @param $image - Profile image of the user
* @param $tweet - Test in the tweet
* @param $created - Date of the tweet
*
* @return Echos out the tweets
*/
private function Display_Tweets($user, $image, $tweet, $created)
{
	echo '
	<div class="pu_fav_tweets">
		<h4><a href="https://twitter.com/'.$user.'">@'.$user.'</a></h4>
		<img src="'.$image.'" alt="'.$user.'" />
		<div class="dashboard-comment-wrap">
		<p>'.$this->hyperlinks($tweet).'</p>
		<p>'.$created.'</p>
	</div>
	</div>';
}

Convert All URLs In Text To Links

When we display tweets most of the tweets are going to have links, if we were going to display the tweet all the links will not be clickable. Therefore we need to create a function to search for URLs in the tweets and make the links clickable.


/**
 * 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',"<a href=\"$1\" class=\"twitter-link\">$1</a>", $text);
    $text = preg_replace('/\b(?<!:\/\/)(www\.[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"<a href=\"http://$1\" class=\"twitter-link\">$1</a>", $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","<a href=\"mailto://$1\" class=\"twitter-link\">$1</a>", $text);
    //mach #trendingtopics. Props to Michael Voigt
    $text = preg_replace('/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)#{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1<a href=\"http://twitter.com/#search?q=$2\" class=\"twitter-link\">#$2</a>$3 ", $text);
    return $text;
}

Full Code

If you followed all the steps above then your code should look like this.


<?php
/*
Plugin Name: Paulund Favourite Tweets Widget
Plugin URI: http://www.paulund.co.uk
Description: Creates a dashboard widget to display your favourite tweets
Version: 1.0
Author: Paulund
Author URI: http://www.paulund.co.uk
*/

// Only display the Fav tweet if on the admin page
if(is_admin()){
	new Paulund_Fav_Tweets_Dashboard_Widget();
}

/**
* Paulund Fav tweets dashboard widget
* This uses the tweet api to get the favourite tweets for a certain user and displays it on the dashboard
*/
class Paulund_Fav_Tweets_Dashboard_Widget
{
	/**
	* Default user to get favourites
	*/
	private $username = "paulund_";

	/**
	* Number of favourite tweets
	*/
	private $limit_tweets = 10;

	/**
	* Constructor to the Fav tweets dashboard widget
	* This will setup the widget and display the tweets
	*/
	public function __construct(){
		add_action( 'wp_dashboard_setup', array(&$this, 'Favs_Dashboard_Setup' ));
		add_action( 'admin_enqueue_scripts', array(&$this, 'load_styles'));
	}

	public function load_styles()
	{
		wp_enqueue_style('fav-tweets', plugins_url( '/paulund-favourite-tweets-widget/css/pu-fav-tweets.css' ));
	}

	/**
	* Setup the dashboard favourites
	*/
	public function Favs_Dashboard_Setup(){
		wp_add_dashboard_widget(
        'fav-tweets-dashboard-widget',
        'Favourite Tweets',
        array(&$this, 'Fav_Tweets_Dashboard_Content'),
        $control_callback = null
    	);
	}

	/**
	* Get the content of the favourite tweets and displays the on the dashboard
	*/
	public function Fav_Tweets_Dashboard_Content(){
		$tweets_array = $this->Get_Fav_tweets($this->username, $this->limit_tweets);

		if($tweets_array != false){
			foreach($tweets_array as $tweets)
			{
				$this->Display_Tweets($tweets->user->screen_name, 
									$tweets->user->profile_image_url_https, 
									$tweets->text, 
									$tweets->created_at);
			}
		}
	}

	/**
	* Display the tweets on the widget
	*
	* @param $user - Username of the tweet
	* @param $image - Profile image of the user
	* @param $tweet - Test in the tweet
	* @param $created - Date of the tweet
	*
	* @return Echos out the tweets
	*/
	private function Display_Tweets($user, $image, $tweet, $created)
	{
		echo '
		<div class="pu_fav_tweets">
			<h4><a href="https://twitter.com/'.$user.'">@'.$user.'</a></h4>
			<img src="'.$image.'" alt="'.$user.'" />
			<div class="dashboard-comment-wrap">
			<p>'.$this->hyperlinks($tweet).'</p>
			<p>'.$created.'</p>
			</div>
		</div>';
	}

	/**
	* Get the fav tweets uses the wordpress remote get function
	*
	* @param $username - User to get fav tweets
	* @param $limit - Limit number of fav tweets
	*
	* @return An array of the favourite tweets
	*/
	private function Get_Fav_tweets($username, $limit){
		$tweets = wp_remote_get('https://api.twitter.com/1/favorites.json?count='.$limit.'&screen_name=' .$username);

		if($tweets['response']['code'] == 200 && !empty($tweets['body'])){
			return json_decode($tweets['body']);
		}

		return false;
	}

	/**
	 * 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',"<a href=\"$1\" class=\"twitter-link\">$1</a>", $text);
	    $text = preg_replace('/\b(?<!:\/\/)(www\.[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"<a href=\"http://$1\" class=\"twitter-link\">$1</a>", $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","<a href=\"mailto://$1\" class=\"twitter-link\">$1</a>", $text);
	        //mach #trendingtopics. Props to Michael Voigt
	    $text = preg_replace('/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)#{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1<a href=\"http://twitter.com/#search?q=$2\" class=\"twitter-link\">#$2</a>$3 ", $text);
	    return $text;
	}
}

?>

Now you can activate this plugin and see all your favourite tweets in the dashboard of your WordPress admin area.