Custom Twitter Feed

Description

Twitter’s standard feed embed is very limited in what it can do. For more design flexibility, it is easier to use developer.twitter.com.

  • Log in using the PHOS Twitter account.
  • Hover over ‘PHOS Creative Devs’ and click “Apps”.
  • In the upper right, click “Create an App”.
  • Fill out the relevant info and click create.
  • Keep that tab open since you’ll need both Consumer API Keys

Use this code snippet to grab the Twitter posts. Change the $api_key and $api_secret variables with their respective keys, as well as $data_username  (change to relevant Twitter account name) and $data_count to the number of Tweets to pull:

// auth parameters
	$api_key = urlencode('APIKEYHERE'); // Consumer Key (API Key)
	$api_secret = urlencode('APISECRETKEYHERE'); // Consumer Secret (API Secret)
	$auth_url = 'https://api.twitter.com/oauth2/token'; 

	// what we want?
	$data_username = 'phoscreative'; // username
	$data_count = 5; // number of tweets
	$data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?tweet_mode=extended';

	// get api access token
	$api_credentials = base64_encode($api_key.':'.$api_secret);

	$auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
					'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'."\r\n";

	$auth_context = stream_context_create(
		array(
			'http' => array(
				'header' => $auth_headers,
				'method' => 'POST',
				'content'=> http_build_query(array('grant_type' => 'client_credentials', )),
			)
		)
	);

	$auth_response = json_decode(file_get_contents($auth_url, 0, $auth_context), true);
	$auth_token = $auth_response['access_token'];

	// get tweets
	$data_context = stream_context_create( array( 'http' => array( 'header' => 'Authorization: Bearer '.$auth_token."\r\n", ) ) );

	$data = json_decode(file_get_contents($data_url.'&count='.$data_count.'&screen_name='.urlencode($data_username), 0, $data_context), true);

	// result - do what you want
	//- print('<pre>');
	//- print_r($data);

 

The $data variable will hold all the information pulled from the Twitter feed. To list the recent Tweets, use the following Jade code:

div(id="twitter-feed")
	main
		img(src="<?php echo esc_url(get_theme_file_uri()) ?>/images/icon-twitter.png", alt="Follow PHOS on Twitter")
		h5 Follow @PHOSCreative
		ul(class="twitter-slider")
			- foreach($data as $tweet) :
				li
					- echo preg_replace('!(http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?%=&_/]+!', "<a href=\"\\0\" target='_blank'>\\0</a>", $tweet['full_text'])
			- endforeach

The foreach loop loops through each Tweet. The “preg_replace” line is a PHP method that searches each Tweet, finds any URLs, and replaces the plain text with a link tag to that respective URL. Lastly, “$tweet[‘full_text’]” is the full text of the Tweet. This is the most basic example of how to use this API, since there is a lot more data to pull from the API call.

MENU