Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Twitter Trends Widget for WordPress

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

In this tutorial we are going to create a WordPress widget that displays Twitter Trends by region. We will use Twitter's Trends API and update trends after a specific time duration using WordPress' Transients API.


Twitter Trends API & WOEID

Twitter Trends: Twitter Trends give a general overview of what the millions of Twitter users are talking about the most at specific time on Twitter, which will give you some indication of what is happening around the world.

Twitter provides a Trends API, GET trends/:woeid, which is a RESTful API that returns results in JSON or XML format. You can easily parse the API request result and display it.

Twitter is using Yahoo’s Where On Earth IDs (WOEIDs) to identify locations for which it has trending data.

So What is WOEID (WHERE ON EARTH IDENTIFIERS) ?
WOEID is a unique reference identifier assigned by Yahoo!'s WOEIDs to identify any place on Earth.


WordPress Widgets

WordPress Widgets are WordPress plugins that can be easily added to widgetized regions of your WordPress theme like the sidebar, footer, etc. To use a WordPress widget you need properly "widgetized" WordPress themes to include widgets in the header, footer, and elsewhere in the WordPress widget areas. From the dashboard administrators can easily add, rearrange, remove and update widget parameters. Using WordPress widgets is very, very easy for non-technical blog owners.

Using WorPress widgets does not require any coding experience. They can be easily added, removed, and rearranged on the WordPress administration "Appearance -> Widgets" panel by simple drag and drop.

Before we start, I assume that you have a general knowledge of the WordPress Widgets API. In this tutorial we are going to use Paulund's WordPress Widget Boilerplate.


Creating Twitter Trends Widget

We are going to create a WordPress widget that allows you to fetch Twitter Trends by region and display them on your WordPress blog / website.

The Twitter Trends Widget gives your blog or website visitors a general overview of what millions of people on Twitter are talking about the most now, based on a specific location. This widget will give some insight in what is happening around the world right now.

Creating the Widget Constructor

Register the 'TwitterTrendsWidget' widget in the widget_init action.

/*
Plugin name: WP Twitter Trends
Plugin URI: http://geekslabs.com/wp-twitter-trends
Description: A widget to show twitter trends by region.
Version: 1.0
Author: Ajay Patel
Author URI: http://ajayy.com 
*/

 
/** 
 * Register the Widget 
 */

add_action( 'widgets_init', 'TwitterTrendsWidgetInit' );
function TwitterTrendsWidgetInit() {
  register_widget( 'TwitterTrendsWidget' );
}

The register_widget function will call the TwitterTrendsWidget class which we will create in the next step.

 /**
 * Adds TwitterTrendsWidget widget.
 */  
class TwitterTrendsWidget extends WP_Widget {
  function TwitterTrendsWidget() {
    parent::WP_Widget( false, $region = 'Twitter Trends Widget' );
  }

  /**
   * Register widget with WordPress.
   */
    public function __construct() {
      parent::__construct(
        'twittertrendswidget', // Base ID
        'TwitterTrendsWidget', // Name
        array( 
        'classname'     =>   'TwitterTrendsWidget', 
        'description' => __( 'A widget to show twitter trends by region.', 'tfwidget' ), ) // Args
      );
    } // End constructor  
  }

Creating the Widget Function

The Widget function helps you to display your widget on the front-end. This function is called to return output of the widget and display it in the widget display area (e.g. sidebar, footer).

As you can see we are collecting all the required fields from the $instance array like title, region, and expiration to display the widget on the website with proper style.

Use the following function to display our Twitter Trends Widget.

  /**
   * Front-end display of widget.
   *
   * @see WP_Widget::widget()
   *
   * @param array $args Widget arguments.
   * @param array $instance Saved values from WordPress transient API.
   */
  function widget( $args, $instance ) {
    extract( $args );    
    $title = apply_filters( 'widget_title', $instance['title'] );
    $region = apply_filters( 'widget_region', $instance['region'] ); // Selected region (Ex. India )
    $expiration = apply_filters( 'widget_expiration', $instance['expiration'] ); // Catch time 
    $display = apply_filters( 'widget_display', $instance['display'] ); // No trends to display 
    
    echo $before_widget;
    
    if ($title) 
    echo $before_title . $title . $after_title; ?>

    <div class="my_textbox">
      <?php
      $trends = twitter_trends($region,$expiration); // Call twitter_trends function
      echo '<ol>';
      for ($i=0; $i < $display; $i++){ 
        echo '<li><a href='.$trends[0]['trends'][$i]['url'].' target="_blank">'.$trends[0]['trends'][$i]['name'].'</a></li>'; // Display Twitter trends
      }
      echo '</ol>';       
      ?>
    </div>

     <?php
       echo $after_widget;
    } ?>

In this Twitter Trends Widget we will use the following variables:

  • $title - Our widget title (textbox field)
  • $region - To select region, default region dropdown with GEOID value, e.g. India: 23424848 (dropdown field)
  • $expiration - Update trends using WordPress Transients API. e.g. hourly, daily (dropdown field)
  • $display - Number of trends to display (textbox field)

We will set the values of these variables using the WordPress $instance variable.

In the code above we are using the twitter_trends() function. You don't need to worry about it now, I will explain it in the next step.

In the function twitter_trends() we are passing $region and $expiration variables and it will return an array of Twitter trends by region. Assign that to the $trends variable.

Next, display trends using a for loop with a limit of displaying trends using the $display variable.

Using WordPress' Transients API.

WordPress' Transients API allows you to store cached data in the database temporarily by giving it a custom name and a time duration after which it will automatically expire and be deleted.

For more information about WordPress' Transients API you can refer to our Getting Started With the WordPress Transients API tutorial series.

  /**
   * Using WordPress transient API
   *
   * @see Transients API : http://codex.wordpress.org/Transients_API
   *
   * @param array $count saved Twitter Trends by region values from Twitter Trends API.
   */

function twitter_trends($region,$expiration){
        
        $count = get_transient('twitter_trends');
    if ($count !== false) return $count;
         $count = 0;

         $url = 'https://api.twitter.com/1/trends/'.$region.'.json?count=50';
         $dataOrig = file_get_contents($url, true); //getting the file content
   if (is_wp_error($dataOrig)) {
         return 'Error while fetching data from Twitter API!';
   }else{
        $count = json_decode($dataOrig, true); //getting the file content as array        
        }

set_transient('twitter_trends', $count, 60*60*$expiration); // set cache
return $count;
}

As I told you before, we are passing two variables $region and $expiration in this function.

Now, using Twitter's Trends API GET trends/:woeid. Suppose our variable $region has a value of "23424848". Let's try to get current Twitter trends for India.

  https://api.twitter.com/1/trends/23424848.json?count=50

Just paste this URL in your your browser. You will see the trends response in JSON format. Using the file_get_contents() reads a file into a string. If there is no error in the response then using json_decode() gets a JSON encoded string and converts it into a PHP object variable $count.

Now update the variable Twitter Trends

set_transient('twitter_trends', $count, 60*60*$expiration); // set cache

Creating Widget Update Function

The WordPress widget update function is used to update our widget form variables to the database by submitting a widget admin form.

    /**
   * 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 = array();

    $instance['title'] = strip_tags( $new_instance['title'] );
    $instance['region'] = strip_tags( $new_instance['region'] );
    $instance['expiration'] = strip_tags( $new_instance['expiration'] );
    $instance['display'] = strip_tags( $new_instance['display'] );
    
    delete_transient( 'twitter_trends' );
    return $instance;    
  }

Widget options were stored in an array variable which was called $instance. The update function takes two parameters, $new_instance and $old_instance. $old_instance which contains all the option values that were already saved before, and $new_instance which contains all of the option values that we have just updated through the widget admin form.

This function sets each old instance value in the array equal to the appropriate value in the new instance.

Creating Widget Form Function

The widget form function is used to create the widget form in the dashboard to store or update widget variables. Creating widget form is very simple, it will output an HTML form with a field for our options.

twitter_trends
  /**
   * Back-end widget form.
   *
   * @see WP_Widget::form()
   *
   * @param array $instance Previously saved values from database.
   */
  function form( $instance ) {
    $title = esc_attr( $instance['title'] );
    $region = esc_attr( $instance['region'] );
    $expiration = esc_attr( $instance['expiration'] );
    $display = esc_attr( $instance['display'] );
    ?>

    <p>
      <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?>
      <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; ?>" />
      </label>
    </p>
    <p>
      <label for="<?php echo $this->get_field_id( 'region' ); ?>"><?php _e( 'Select Region:' ); ?>
      <select class="widefat" name="<?php echo $this->get_field_name( 'region' ); ?>">
        <option value="23424975" <?=$region == '23424975' ? ' selected="selected"' : '';?>>United Kingdom</option>
        <option value="2450022" <?=$region == '2450022' ? ' selected="selected"' : '';?>>Miami</option>
        <option value="1118129" <?=$region == '1118129' ? ' selected="selected"' : '';?>>Sendai</option>
        <option value="23424908" <?=$region == '23424908' ? ' selected="selected"' : '';?>>Nigeria</option>
        <option value="2458833" <?=$region == '2458833' ? ' selected="selected"' : '';?>>New Orleans</option>
      </select>  
      </label>
    </p>
    <p>
      <label for="<?php echo $this->get_field_id( 'expiration' ); ?>"><?php _e( 'Update Trends :' ); ?>
      <select class="widefat" name="<?php echo $this->get_field_name( 'expiration' ); ?>">
        <option value="1" <?=$expiration == '1' ? ' selected="selected"' : '';?>>Hourly</option>
        <option value="12" <?=$expiration == '12' ? ' selected="selected"' : '';?>>Twice Daily</option>
        <option value="24" <?=$expiration == '24' ? ' selected="selected"' : '';?>>Daily</option>
        <option value="168" <?=$expiration == '168' ? ' selected="selected"' : '';?>>Weekly</option>
        <option value="720" <?=$expiration == '720' ? ' selected="selected"' : '';?>>Monthly</option>
      </select>
      </label>
    </p>
    <p>
      <label for="<?php echo $this->get_field_id( 'display' ); ?>"><?php _e( 'Display Number of Trends :' ); ?>
      <input class="widefat" id="<?php echo $this->get_field_id( 'display' ); ?>" name="<?php echo $this->get_field_name( 'display' ); ?>" type="text" value="<?php echo $display; ?>" />
      </label>
    </p>
    
    <?php
  }
} // class TwitterTrendsWidget
?>

In this function you can see the $instance parameter, which allows our HTML form to read the saved widget options.


Putting It Together: The Full Code

You can see the full code in the WP Twitter Trends plugin in the WordPress.org plugin directory, or download it from the link at the top of this article.


Conclusion

And here we have successfully developed a WP Twitter Trends Widget! You can download the source code and change the front-end widget layout by adding new CSS styles. You can also create a tabbed widget to separate latest trends topic and hashtags. Now you have a trends widget on your site or blog.

Thanks for reading my article! If you have any questions or doubts in your mind just leave a comment, I'm glad to help you in the comments.

Advertisement