How to Create a Twitter Widget?

Twitter is one of the largest social networks in the World and to create a Twitter widget programmers have to follow the every detail that is described. After the completion of the project, developers need to streamline the widget according to Twitter Developer Display Requirements, failing to which may lead to banned ID.

Twitter Widget

Creating a Twitter Application

Twitter API credentials are required before coding is begun. The steps to create a Twitter application are:

  1. Log onto Twitter developer section.
  2. Go to My Applications; click on “create a new application”.
  3. Fill in the required fields and accept the rules. Click on “create your Twitter application”. Call back URL is not required for this application.
  4. Click on “create my access token”.
  5. Following data will be required later:
  • Access token and access token secret
  • Consumer key and consumer key secret

Adding Details to Application

Theme customizer of WordPress 3.4 can be used to quickly add options to the theme. Only bare necessities need to be added.
The following snippet can be used to quickly access theme customizer:
add_action (‘admin_menu’, ‘my_theme_customizer’);
function my_theme_customizer() {
__( ‘Customize Theme Options’, THEMENAME ),
__( ‘Customize Theme’, THEMENAME ),
Codes can be added above functions.php to create link to “Appearance section” in admin panel. A class is required to add options. Add MyCustomizer.class.php to theme directory and paste following codes:
class MyCustomizer {
public static function register ( $wp_customize ) {

/** Sections **/
$wp_customize->add_section( ‘twitter_api’ , array(
‘title’ => __( ‘Twitter API Details’, ‘mytextdomain’ ),
‘priority’ => 10,

/** Settings **/
$wp_customize->add_setting( ‘twitter_consumer_key’ );
$wp_customize->add_setting( ‘twitter_consumer_secret’ );
$wp_customize->add_setting( ‘twitter_access_token’ );
$wp_customize->add_setting( ‘twitter_access_token_secret’ );

/** Controls **/
‘label’ => __( ‘Consumer Key’, ‘mytextdomain’ ),
‘section’ => ‘twitter_api’,
‘priority’ => 10,
‘label’ => __( ‘Consumer Secret’, ‘mytextdomain’ ),
‘section’ => ‘twitter_api’,
‘priority’ => 20,
‘label’ => __( ‘Access Token’, ‘mytextdomain’ ),
‘section’ => ‘twitter_api’,
‘priority’ => 30,
‘label’ => __( ‘Access Token Secret’, ‘mytextdomain’ ),
‘section’ => ‘twitter_api’,
‘priority’ => 40,
add_action( ‘customize_register’ , array( ‘MyCustomizer’ , ‘register’ ) );
The class registered at the end of the code black by a hook contains the encapsulated details that need to be added to the customizer.

Following have to be done to display the options:

  • Use add_section() to make a new section for holding options in single logical group. Add a title.
  • Use add_settings() to inform WordPress about addition of particular settings. Its default parameters are not needed here.
  • Specify settings to be modified, control labels and its section under add_control(). Input box is the default type of control.

Priority settings for elements determine the order of their display. Multiples of 10 can be used to avoiding rewriting all the priorities when something needs to be added between two settings.
Include functions.php to execute the codes. Fill in the details. Use get_theme_mod(‘option_name’) to access values.

Integrating the API

Although API details can be retrieved by now, the contact with it is yet to be established, which is tough. PHP class Codebird can be used to interact with Twitter API. Download codebird.php, put in the main theme folder, set it like:
add_action( ‘init’, ‘my_twitter_api’ );
function my_twitter_api() {
global $cb;
$consumer_key = get_theme_mod( ‘consumer_key’ );
$consumer_secret = get_theme_mod( ‘consumer_secret’ );
$access_token = get_theme_mod( ‘access_token’ );
$access_secret = get_theme_mod( ‘access_secret’ );

include( ‘codebird.php’ )
Codebird::setConsumerKey( $consumer_key, $consumer_secret );
$cb = Codebird::getInstance();
$cb->setToken( $access_token, $access_secret );
Now, $cb instance can be invoked to use codebird. It will be needed later.

Creating a Widget

Dividing widgets into separate files is often preferable. To do this, create a widget directory and put MyTwitterWidget.class.php into it. Include this file into functions.php() by:
include( ‘widgets/MyTwitterWidget.class.php’ );
The following code-block is the starting point for widget development:
class MyTwitterWidget extends WP_Widget {
/** Widget setup **/
function MyTwitterWidget() {
false, __( ‘My Twitter Widget’, ‘mytextdomain’ ),
array(‘description’ => __( ‘Displays a list of tweets from a specified user name’, ‘mytextdomain’ )),
array(‘width’ => ‘400px’)
/** The back-end form **/
function form( $instance ) {

/** Saving form data **/
function update( $new_instance, $old_instance ) {

/** The front-end display **/
function widget( $args, $instance ) {

Each of the four functions in the code-block has a particular part in widget development.

  • First Function: It is a conductor. Title and description of widget can be specified in it.
  • Form Function: It is responsible for backend forms. A few functions can be put into it to make assembly of forms easy. WordPress does the rest.
  • Update Function: It allows addition of special codes to the process.
  • Widget Function: It controls the display of widgets.

Custom functions will be required later in the development.

The Back-End Form

Users should be enabled to specify their username, specify the number of tweets to be displayed and change the widget title. It can be done with the following code-block:
<label for='<?php echo $this->get_field_id( ‘option_name’ ); ?>’>
<?php _e( ‘Title:’, ‘mytextdomain’ ); ?>
<input class=’widefat’ id='<?php echo $this->get_field_id( ‘option_name’ ); ?>’ name='<?php echo $this->get_field_name( ‘option_name’ ); ?>’ type=’text’ value='<?php echo $values[‘option_name’]; ?>’ />
All the options of the widget that are specified elsewhere are enlisted in the array $values. Two functions become crucial multiple sidebars have multiple widget instances:
get_field_id() :It outputs field ID for the option.
get_field_name() :It outputs the field name of the option.
Following is the complete code-block for the form:
$defaults = array(
‘title’ => ”,
‘limit’ => 5,
‘username’ => ‘bonsaished’
$values = wp_parse_args( $instance, $defaults );
<label for='<?php echo $this->get_field_id( ‘title’ ); ?>’>
<?php _e( ‘Title:’, ‘mytextdomain’ ); ?>
<input class=’widefat’ id='<?php echo $this->get_field_id( ‘title’ ); ?>’ name='<?php echo $this->get_field_name( ‘title’ ); ?>’ type=’text’ value='<?php echo $values[‘title’]; ?>’ />

<label for='<?php echo $this->get_field_id( ‘limit’ ); ?>’>
<?php _e( ‘Tweets to show:’, ‘mytextdomain’ ); ?>
<input class=’widefat’ id='<?php echo $this->get_field_id( ‘limit’ ); ?>’ name='<?php echo $this->get_field_name( ‘limit’ ); ?>’ type=’text’ value='<?php echo $values[‘limit’]; ?>’ />

<label for='<?php echo $this->get_field_id( ‘username’ ); ?>’>
<?php _e( ‘Twitter user name:’, ‘mytextdomain’ ); ?>
<input class=’widefat’ id='<?php echo $this->get_field_id( ‘username’ ); ?>’ name='<?php echo $this->get_field_name( ‘username’ ); ?>’ type=’text’ value='<?php echo $values[‘username’]; ?>’ />
Pass the function into $instance parameter. Add an array defaults, if not value is set. The final array $values is the merger of instance and defaults.

Saving the Form Data

Following is the coding in function update() :
return $new_instance;
The parameter $new_instance contains all the new data and needs to be returned. Update function allows validation or manipulation.

Displaying the Tweets

Retrieval of tweets is not difficult but doing it in every page load will draw rate-limit by Twitter. The results have to be cached to allow larger intervals between calling Twitter. Such issues can be side-stepped altogether and coded as if the solution was present. The functions for this will be provided later.
Following template is required to display widgets:
echo $args[‘before_widget’];
echo $args[‘before_title’] . $instance[‘title’] . $args[‘after_title’];
echo $args[‘after_widget’];
The parameter $args contains structural information of the created sidebar. They are output to validate conformity of this widget with others.
List some tweets by the following codes:
$tweets = $this->get_tweets( $args[‘widget_id’], $instance );
if( !empty( $tweets[‘tweets’] ) AND empty( $tweets[‘tweets’]->errors ) ) {

echo $args[‘before_widget’];
echo $args[‘before_title’] . $instance[‘title’] . $args[‘after_title’];

$user = current( $tweets[‘tweets’] );
$user = $user->user;

echo ‘
<div class=”twitter-profile”>
<img src=”‘ . $user->profile_image_url . ‘”>
<h1><a class=”heading-text-color” href=”’ . $user->screen_name . ‘”>’ . $user->screen_name . ‘</a></h1>
<div class=”description content”>’ . $user->description . ‘</div>
</div> ‘;

echo ‘<ul>’;
foreach( $tweets[‘tweets’] as $tweet ) {
if( is_object( $tweet ) ) {
$tweet_text = htmlentities($tweet->text, ENT_QUOTES);
$tweet_text = preg_replace( ‘/http://([a-z0-9_.-+&!#~/,]+)/i’, ‘http://$1’, $tweet_text );

echo ‘
<span class=”content”>’ . $tweet_text . ‘</span>
<div class=”date”>’ . human_time_diff( strtotime( $tweet->created_at ) ) . ‘ ago </div>
echo ‘</ul>’;
echo $args[‘after_widget’];

  • Line 1: get_tweets() is assumed to be ready to realise what to incorporate to function code.
  • Line 2: Widget can be displayed provided errors do not exist and tweet list in not empty.
  • Line 7-8: First tweet is captured in line-7 and user details are pulled into variable $user in line-8.
  • Line 10-16: Data in $user is used to create user account display with username, image and short description.
  • Line 18-29: Data in $tweets[‘tweets’] is used to build a tweets list. preg_replace() make links clickable.

Implement the following to enable get-tweets() to get tweets:

  1. Obtain tweets list from own database.
  2. It captures the list from Twitter, if the list is older than 5 minutes or absent.
  3. Save the captured result to the database. Add timestamp to avoid the same result until 5 minutes.

Following 3 functions make it more modular:

  • get-tweets() :It pulls tweets list from native database.
  • retrieve_tweets() :It pulls tweets list from Twitter.
  • Save_tweets :It saves tweets list from Twitter to native database.

Retrieving Tweets from Twitter

Create the following function in MyTwitterWidget to retrieve some tweets:
function retrieve_tweets( $widget_id, $instance ) {
global $cb;
$timeline = $cb->statuses_userTimeline( ‘screen_name=’ . $instance[‘username’]. ‘&count=’ . $instance[‘limit’] . ‘&exclude_replies=true’ );
return $timeline;

Saving Tweets to Database

Tweets and widget ID are required to save tweets. The time of last update has to be stored.
function save_tweets( $widget_id, $instance ) {
$timeline = $this->retrieve_tweets( $widget_id, $instance );
$tweets = array( ‘tweets’ => $timeline, ‘update_time’ => time() + ( 60 * 5 ) );
update_option( ‘my_tweets_’ . $widget_id, $tweets );
return $tweets;
retrieve_tweets() uses the received instance data and widget ID to retrieve tweets, which will be added to $tweets, which contains update time and returned data.

Getting Tweets from Database

function get_tweets( $widget_id, $instance ) {
$tweets = get_option( ‘my_tweets_’ . $widget_id );
if( empty( $tweets ) OR time() > $tweets[‘update_time’] ) {
$tweets = $this->save_tweets( $widget_id, $instance );
return $tweets;


Although this method is complex, it has clear logic, which is due to the way WordPress implements theme customizer and widgets.

Find Detailed Answers to the Question of How to Integrate Social Media into Your Website

Integrating social media to a website is one of the latest trends. It can be seen in most of the websites worldwide. Basically there has been a great craze of social networks for the past few years.  The number of users in these social networks has taken an exponential curve from their birth till today. No matter what work a person is one doing with his/her laptop, PC or mobile phone, they are always connected to one or the other social networks.

It is a good place of making new friends, stay connected to the friends and sharing photos or videos with others. But moreover it is a huge platform to share new ideas and views and get a mass public reaction to them. Here comes the importance of integrating social media into a website. Now the question of how to integrate social media into your website may arise in the mind of many people.  Well as an answer to this question it must be stated that it can be done in some simple steps, without much effort or stress.

Know How to Integrate Social Media into Your Website

How to Integrate Social Media into Your Website

Now-a-days most of the companies post their products and concepts on the social sites before launching them. This helps greatly to gain feedbacks on the products or concepts. Posting them in the social networks gives a huge recognition to the products since most of the people are registered with the sites and it can be viewed by the members throughout the world. Hence social media is necessary for a website to get it connected to any social networks. Now let’s come to the point how to integrate social media into your website. There are many processes for the integration. Basically there are specific processes for different social networking sites. For example, the #tweetme options for twitter, fbshare button for Facebook, dig button and widgets for digg, RSS feedbacks etc.

They are integrated to the websites through some coding and connections. So whenever one is viewing the website and if the visitor clicks the specific button, it is directly uploaded to the social network. Hence the views between the users can be shared and a mass feedback can be created easily. Socializing these products also help in further development and overcoming the cons of the product. The best places for the social media buttons are on the top, bottom or along the side of the homepage of the site. Linking more than one social site is more practical. But the integrations must be made in the places where it makes proper sense.  Update and share buttons are a must to include. But overusing the social media is not at all suggestible. It will give a negative outlook to the viewers.

Socializing a website is quite helpful to the viewers as well as to the company. There are no other better ways than the social sites to get huge viewers throughout the world to share their opinions over anything. The credit goes to the API of most of the social networks that they are increasing more options on how to integrate social media into your website and thus providing a helpful service.