Social Media is very important for bloggers and also for business websites. A better way to connect Twitter with a website is by creating a Twitter Feed for that website.
In this article, I'm going to show how to talk to the Twitter API and fetch data from Twitter.
For doing so, you need three things:
- Twitter username
- Consumer key
- Consumer Secret key
You can get those data from your Twitter app.
Check my other articles:
Hey, WordPress devs. Try Python
WordPress post view count
The concept is pretty simple and straight forward. At first, you'll do the authentication, then use that authentication and sent a request to Twitter for your Twitter feed data.
It's like you went to a bank, showed your identity and other papers for verifications, and then they'll sanction your loan request.
Yeah... sounds funny. You need to verify yourself for your own data. But the Bottom line is "That's how the world works".
Now let's see how things work together...
$user_name = "your twitter user name";
$consumer_key = "your twitter app consumer key";
$consumer_secret_key = "your twitter app consumer secret key";
$credentials = base64_encode( $consumer_key . ':' . $consumer_secret_key );
$auth_response = wp_remote_post( 'https://api.twitter.com/oauth2/token',
array(
'method' => 'POST',
'httpversion' => '1.1',
'blocking' => true,
'headers' => [
'Authorization' => 'Basic ' . $credentials,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8',
],
'body' => ['grant_type' => 'client_credentials'],
) );
$body = json_decode( wp_remote_retrieve_body( $auth_response ) );
$token = $body->access_token;
$tweets_response = wp_remote_get( 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $user_name . '&count=900&tweet_mode=extended',
array(
'httpversion' => '1.1',
'blocking' => true,
'headers' => [ 'Authorization' => "Bearer $token", ],
) );
$twitter_data = json_decode( wp_remote_retrieve_body( $tweets_response ), true );
if ( !array_key_exists( 'errors', $twitter_data ) && !empty( $twitter_data ) ) {
print_r( $twitter_data ); // Hell Yeah, you did it...
}
You can also add something called transient
for better performance. I'll write an article only on Transient very soon.
Top comments (0)