Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Retrieve Your Twitter Follow Count (and Other Data) in Plain Text With WordPress Shortcode or PHP

This article provides the necessary code to query Twitter for profile data relevant to your (and other) accounts. Once we retrieve the data from Twitter we cache the resulting array with Simple Cache to avoid repeated requests to the API. While we cache the most relevant user data, it's the follower count that we've found users are most interested in using. That said, the function is handy for retrieving your latest tweet (another post is forthcoming that shows you how to build a sidebar widget).

The function requires you install Abraham's twitteroauth . We have an old video here that'll show you how to set up your Twitter application .

The Result

The function works by finding and replacing relevant keywords in your text with the appropriate response from our cached Twitter array. For this reason we're required to use opening and closing shortcode tags. The most common response required is the follower count, and this may be returned with [twitterdata]%%followers%%[/twitterdata].

Since we're retrieving the Twitter array from a cached source, we don't make another request to the API despite returning a different result.

Common Functions

The common functions are required for use with both the PHP application and WordPress shortcode. Its purpose is to query Twitter and cache the resulting array of profile information. If you're using the function from within WordPress, you won't need to include Simple Cache; instead, install the plugin.

1
<?php 
2
/*
3
 Retrieve Twitter Data With WordPress Shortcode or PHP
4
 http://www.beliefmedia.com/twitter-data
5
 Include Simple Cache & twitteroauth
6
*/
7
 
8
include('../simple-cache/cache.inc.php');
9
require_once ('/home/your/public_html/library/twitteroauth/autoload.php');
10
use Abraham\TwitterOAuth\TwitterOAuth;
11
 
12
/*
13
 Retrieve Twitter Data With WordPress Shortcode or PHP
14
 http://www.beliefmedia.com/twitter-data
15
*/
16
 
17
function beliefmedia_twitter_statistics($keys, $cache = '10800') {
18
 
19
  /* Check for Simple Cache */
20
  if (!function_exists('beliefmedia_get_transient')) return '<a href="http://www.beliefmedia.com/simple-php-cache">Simple Cache</a> is required.';
21
 
22
  /* Get cached data */
23
  $transient = 'twitter_data_' . md5(serialize(func_get_args()));
24
  $cached = beliefmedia_get_transient($transient, $cache);
25
  if ($cached !== false) return $cached;
26
 
27
  /* New request */
28
  $twitter_api = new TwitterOAuth($keys['ck'], $keys['cs'], $keys['at'], $keys['ats']);
29
  $twitter_api_link = $twitter_api->get('account/verify_credentials' , array('include_entities' => (false)));
30
 
31
    if ($twitter_api->getLastHttpCode() == '200') {
32
 
33
      $response = array();
34
 
35
      /* Selecting only limited data.. */
36
      $response['userid'] = $twitter_api_link->id;
37
      $response['followers'] = $twitter_api_link->followers_count;
38
      $response['following'] = $twitter_api_link->friends_count;
39
      $response['created'] = $twitter_api_link->created_at;
40
      $response['name'] = $twitter_api_link->name;
41
      $response['screenname'] = $twitter_api_link->screen_name;
42
      $response['location'] = htmlentities($twitter_api_link->location, ENT_QUOTES);
43
      $response['description'] = htmlentities($twitter_api_link->description, ENT_QUOTES);
44
      $response['count'] = $twitter_api_link->statuses_count;
45
      $response['profileurl'] = $twitter_api_link->profile_image_url;
46
      $response['lasttweet'] = htmlentities($twitter_api_link->status->text, ENT_QUOTES);
47
 
48
      /* Cache data */
49
      beliefmedia_set_transient($transient, $response);
50
    }
51
 
52
 return (is_array($response)) ? $response : false;
53
}

If you wanted to test the function and view the resulting array, use the following:

1
<?php 
2
$keys = array('ck' => 'xxx', 'cs' => 'xxx', 'at' => 'xxx', 'ats' => 'xxx');
3
echo 'pre' . print_r(beliefmedia_twitter_statistics($keys), true) . '/pre';

Ensure you add the pre HTML tags (removed for formatting).

We use a function to linkify links, usernames, and hashtags. The function is required and available here.

WordPress Shortcode

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Retrieve Twitter Data With WordPress Shortcode or PHP
4
 http://www.beliefmedia.com/twitter-data
5
*/
6
 
7
function beliefmedia_twitter_data($atts, $content = null) {
8
 
9
  $atts = shortcode_atts(array(
10
    'ck' => 'xxxxxxxxxxxxxxxxxxx',
11
    'cs' => 'xxxxxxxxxxxxxxxxxxx',
12
    'at' => 'xxxxxxxxxxxxxxxxxxx',
13
    'ats' => 'xxxxxxxxxxxxxxxxxxx',
14
    'p' => 0,
15
    'style' => 'text-decoration: none;',
16
    'cache' => 3600 * 8
17
  ), $atts);
18
 
19
 /* Check for the linkify function */
20
 if (!function_exists('beliefmedia_linkify_twitter')) return 'The <a href="http://www.beliefmedia.com/code/php-snippets/linkify-twitter">Twitter Linkify</a> function is required.';
21
 
22
 $transient = 'bmtd_' . md5(serialize($atts) . $content);
23
 $cached =  get_transient($transient);
24
 
25
 if ($cached !== false ) {
26
  return $cached;
27
 
28
  } else {
29
 
30
    /* Get Twitter data */
31
    $data = beliefmedia_twitter_statistics($atts, $cache = '21600');
32
    if ($data === false) return 'Error. Try again soon.';
33
      else extract($data);
34
 
35
      /* Find & Replace Patterns */
36
      $twitter_patterns = array(
37
        '%%userid%%' => $userid,
38
        '%%followers%%' => number_format($followers),
39
        '%%following%%' => number_format($following),
40
        '%%created%%' => date( ('F j, Y, g:i a'), strtotime($created) ),
41
        '%%name%%' => $name,
42
        '%%screenname%%' => $screenname,
43
        '%%location%%' => $location,
44
        '%%description%%' => beliefmedia_linkify_twitter($description),
45
        '%%count%%' => number_format($count),
46
        '%%profileurl%%' => $profileurl,
47
        '%%lasttweet%%' => beliefmedia_linkify_twitter($lasttweet)
48
      );
49
 
50
      foreach ($twitter_patterns as $search => $replace) {
51
        $content = str_replace($search, $replace, $content);
52
      }
53
 
54
    /* Apply style */
55
    $return = '<span style="' . $style . ';">' . $content . '</span>';
56
    if ($atts['p']) $return = '' . $return . '';
57
 
58
    /* Cache result */
59
    set_transient($transient, $content, $atts['cache']);
60
 
61
   /* Return result */
62
   return $return;
63
 }
64
}
65
add_shortcode('twitterdata', 'beliefmedia_twitter_data');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

PHP Function

The PHP function is intended to be used outside of WordPress. It includes fewer options than the shortcode; the assumption is that you'll curate the result to your liking.

1
<?php 
2
/*
3
 Retrieve Twitter Data With WordPress Shortcode or PHP
4
 http://www.beliefmedia.com/twitter-data
5
*/
6
 
7
function beliefmedia_twitter_data($content, $keys, $cache = '21600') {
8
 
9
 /* Check for the linkify function */
10
 if (!function_exists('beliefmedia_linkify_twitter')) return 'The <a href="http://www.beliefmedia.com/code/php-snippets/linkify-twitter">Twitter Linkify</a> function is required.';
11
 
12
 $transient = 'bm_twitter_data_' . md5(serialize(func_get_args()));
13
 $cached =  beliefmedia_get_transient($transient, $cache);
14
 
15
 if ($cached !== false ) {
16
  return $cached;
17
 
18
  } else {
19
 
20
    /* Get Twitter data */
21
    $data = beliefmedia_twitter_statistics($keys, $cache);
22
    if ($data === false) return 'Error. Try again soon.';
23
      else extract($data);
24
 
25
      /* Find & Replace Patterns */
26
      $twitter_patterns = array(
27
        '%%userid%%' => $userid,
28
        '%%followers%%' => number_format($followers),
29
        '%%following%%' => number_format($following),
30
        '%%created%%' => date( ('F j, Y, g:i a'), strtotime($created) ),
31
        '%%name%%' => $name,
32
        '%%screenname%%' => $screenname,
33
        '%%location%%' => $location,
34
        '%%description%%' => beliefmedia_linkify_twitter($description),
35
        '%%count%%' => number_format($count),
36
        '%%profileurl%%' => $profileurl,
37
        '%%lasttweet%%' => beliefmedia_linkify_twitter($lasttweet)
38
      );
39
 
40
      foreach ($twitter_patterns as $search => $replace) {
41
        $content = str_replace($search, $replace, $content);
42
      }
43
 
44
    /* Cache result */
45
    beliefmedia_set_transient($transient, $content);
46
 
47
   /* Return result */
48
   return $content;
49
 }
50
}
51
 
52
/* Usage */
53
$keys = array('ck' => 'xxxx', 'cs' => 'xxxx', 'at' => 'xxxx', 'ats' => 'xxxx');
54
$content = '%%lasttweet%% - Join %%followers%% and follow us on Twitter.';
55
echo beliefmedia_twitter_data($content, $keys);

Data returned via the PHP function is cached via Simple Cache.

Considerations

  • An example response of the $data array that we cache is as follows:

    1
    Array
    2
    (
    3
        [userid] => 65249446
    4
        [followers] => 8117
    5
        [following] => 6950
    6
        [created] => Thu Aug 13 02:43:01 +0000 2009
    7
        [name] => Belief Media
    8
        [screenname] => BeliefMedia
    9
        [location] => Australia.
    10
        [description] => BeliefMedia is Sydney's fastest growing media & marketing company. Simply put, we make businesses grow... bigly 🙂
    11
        [count] => 538
    12
        [profileurl] => http://pbs.twimg.com/profile_images/753827278014984192/5BS5q-Ga_normal.jpg
    13
        [lasttweet] => Simple Responsive Pricing Tables With #WordPress Shortcode https://t.co/RgW0O2wX7u - @BeliefMedia
    14
    )
  • When registering your Twitter application, be sure to select Read/Write as the application privilege. You will be required to have a verified phone number before this option becomes available.

Download


Title: Retrieve Twitter Data With WordPress Shortcode or PHP (Shortcode)
Description: Retrieve Your Twitter Follow Count (and Other Data) in Plain Text With WordPress Shortcode or PHP. Data is cached.
  Download • Version 0.2, 1.7K, zip, Category: WordPress Shortcodes
PHP Code & Snippets, (1.6K)    

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Washington)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433