Twitter Feed on WordPress

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:

  1. Twitter username
  2. Consumer key
  3. Consumer Secret key

You can get those data from your Twitter app.

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.

Now let’s see how things work together…

At first let’s bring the “Access Token” —

$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( '',
                    '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;

Now send a get request by using that access token —

$tweets_response = wp_remote_get( '' . $user_name . '&count=900&tweet_mode=extended',
                    '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.

5 1 vote
Article Rating