Create custom Twitter Widget using PHP


Twitter Embedded timelines are an easy way to display multiple Tweets on your website. You can easily implement Twitter Embedded Timelines into your website from twitter widgets creation section. But some time we need to customize twitter feed as per our project needs. In this tutorial we’ll discuss how to build custom twitter feed using PHP.

We will use TwitterOAuth PHP Library for Authentication with Twitter. Consumer Key (API Key), Consumer Secret (API Secret), Access Token and Access Token Secret are needed for authentication. You should create the Twitter Application first to get these details. If you are need help, you can read our tutorial: How to Create Twitter OAuth Application

TwitterOAuth PHP Library can be found from our downloadable package. Include the TwitterOAuth PHP Library and define some required configuration variables. Using TwitterOAuth PHP Library we will authenticate with Twitter and get the user timeline feeds by Twitter ID. Full code are given below.

//Path to TwitterOAuth library

$twitterID "semicolonworldblog";
$tweetNum 10;
$consumerKey "InsertConsumerKey";
$consumerSecret "InsertConsumerSecret";
$accessToken "InsertAccessToken";
$accessTokenSecret "InsertAccessTokenSecret"
$twitterID && $consumerKey && $consumerSecret && $accessToken && $accessTokenSecret) {
//Authentication with twitter
$twitterConnection = new TwitterOAuth(
//Get user timeline feeds
$twitterData $twitterConnection->get(
'screen_name'     => $twitterID,
'count'           => $tweetNum,
'exclude_replies' => false
<div class="tweet-box"> <h1>Tweets</h1> <div class="tweets-widget"> <ul class="tweet-list"> <?php if(!empty($twitterData)): foreach($twitterData as $tweet): $latestTweet = $tweet->text; $latestTweet = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a class="tweet-author" href="$1" target="_blank">@$1</a>', $latestTweet); $tweetTime = date("D M d H:i:s",strtotime($tweet->created_at)); ?> <li class="tweet-wrapper"> <div class="tweet-thumb"> <span class="had-thumb"><a href="<?php echo $tweet->user->url; ?>" title="<?php echo $tweet->user->name; ?>"><img alt="" src="<?php echo $tweet->user->profile_image_url; ?>"></a></span> </div> <div class="tweet-content"> <h3 class="title" title="<?php echo $tweet->text; ?>"><?php echo $latestTweet; ?></h3> <span class="meta"><?php echo $tweetTime; ?> - <span><span class="dsq-postid" rel="8286"><?php echo $tweet->favorite_count; ?> Favorite</span></span></span> </div> </li> <?php endforeach; else: ?> <li class="tweet-wrapper">Tweets not found for the given username.</li> <?php endif; ?> </ul> </div> </div> <?php
'Authentication failed, please try again.';

We will use some css (style.css) for styling the custom Twitter widget.

Related Articles

Comments 0