: Undefined variable $bodyClass in /home/shtechno/public_html/shivamkhare.in/wp-content/themes/shivam/header.php on line 50
class="post-template-default single single-post postid-89 single-format-standard vertical">
In this blog, you’ll learn how to implement Twitter API with PHP or WordPress and show your tweets on your custom HTML format.
Get the API key & API secret key from Twitter’s dev portal.
If you haven’t already, so you follow this Link to get your Keys or follow the article How to get Twitter API Keys or Access Token.
Add this code to your function.php or add your API key & API secret key, which get by first step.
function get_twitter_access(){
$key = ''; // Consumer Key (API Key)
$secret = ''; // Consumer Secret (API Secret)
$response = wp_remote_post( 'https://api.twitter.com/oauth2/token', array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( urlencode( $key ) . ':' . $secret ),
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
),
'body' => 'grant_type=client_credentials'
) );
$body = json_decode( $response['body'] );
return $body->access_token;
}
Display all tweets on users timeline use 1.1/statuses/user_timeline.json.
<?php $token = get_twitter_access(); // that's our token from the previous step
$args = array(
'headers' => array(
'Authorization' => 'Bearer ' . $token
)
);
$response = wp_remote_get( add_query_arg( array(
'count' => 3, // how much to display
'screen_name' => 'RealShivamKhare', // favorites of user @RealShivamKhare
'include_entities' => true,
'tweet_mode' => 'extended',
), 'https://api.twitter.com/1.1/statuses/user_timeline.json' ), $args );
$tweets = json_decode( $response['body'] );
$tweets_html = '';
foreach( $tweets as $tweet ) {
$tweetimg = $tweet->entities->media[0]->media_url;
echo '<div class="col-md-4 col-sm-6 col-xs-6">
<a href="https://twitter.com/SRI_Intl/status/'.$tweet->id.'" class="" target="_blank" >
<div class="works-image bg-img" '.(($tweetimg)?'style="background-image:url('.$tweetimg.')"': '').'></div><div class="slider-content"><p><span>'.date( 'Y-m-d H:i:s', strtotime( $tweet->created_at ) ).'</span></p><h4>'.$tweet->full_text.'</h4></div>
</a>
</div>';
} ?>
// more params in Twitter docs
https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
If you want to displays only favorites tweets use this 1.1/favorites/list.json, that were marked by a specific user as favorite (the heart button clicked).
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list
For more endpoints please visit Twitter API reference.