RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Retrieve Twitter Favorites (Likes) and Display in WordPress with Shortcode

Retrieve Twitter Favorites (Likes) and Display in WordPress with Shortcode

At the time of originally writing this article (March, 2016), Twitter had just renamed their Twitter favorites to "likes" (expressed by way of a little heart signal) in a puerile attempt at remaining relevant in a world dominated by Facebook. The change likely comes from the fact that the word 'favorite' isn't generally culturally-compatible because of the implied variations in translation, while a heart signal is a globally accepted symbol that transcends language. The change was just another to the platform in the months preceding to maintain relevance.

Note: While the code provided is functional, we've removed the examples as the website itself no longer requires Twitter support.

While the word "like" generally translates to "enjoy" in common language, it is inconsistent with the picture representation; likes (the heart) and favorites are very different things. I usually favorite tweets as a bookmark - not necessarily because I like them... and 'hearting' a tweet sends a very different message. If you look at my favorites you'll see tweets that I've often saved because I didn't like them. Changing what favorites are will change how they're used, and potentially alters all existing favorites as well.

Sometimes, however, it's nice to keep a list of your favorites 'likes' on your WordPress website as a resource for others, and they're a convenient way to bookmark tweets for your own reading. The WordPress shortcode on this page will render your favorites in a very basic manner.

The Result

For the purpose of this article I'll render just three favorites. To see a more comprehensive list, see this example page (50 results). To render the three likes below, I've used the shortcode of [twitterlikes user="MartyKhoury" num="3"]. I could have omitted my username because I've listed it as a default in my code.

To display the likes of another use, substitute your own username for theirs. A maximum of 200 favorites can be returned in the one request. More details below.

Registering a Twitter Application

You must have a Twitter application registered. In doing so you'll create a $consumerkey, $consumersecret, $accesstoken, and $accesstokensecret that are all required in the shortcode function. You should refer to this video on setting up the necessary application on Twitter.

We're using Abraham Williams' TwitterOAuth library to assist with making the request. The library must be included at the top of your custom functions file (you'll need to reference the path to the autoload.php file).

1
<?php 
2
require '/home/path/to/home/twitteroauth/autoload.php';
3
use Abraham\TwitterOAuth\TwitterOAuth;

The Code

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 Favorites (Likes) and Display in WordPress with Shortcode
4
 http://www.beliefmedia.com/twitter-likes
5
*/
6
 
7
function beliefmedia_twitter_likes($atts) {
8
 
9
  $atts = shortcode_atts(array(
10
    'user' => 'MartyKhoury',
11
    'num' => '50',
12
    'cache' => 3600 * 24 * 7
13
  ), $atts);
14
 
15
 $transient = 'bmtwf_' . md5(serialize($atts));
16
 $cached =  get_transient($transient);
17
 
18
 if ($cached !== false ) {
19
  return $cached;
20
 
21
  } else {
22
 
23
    /* Twitter keys */
24
    $consumerkey = 'xxxxxxxxxxxxxxxxxxxxxx';
25
    $consumersecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
26
    $accesstoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
27
    $accesstokensecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
28
 
29
    $connection = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
30
    $tweets = $connection->get('favorites/list', array('screen_name' => $atts['user'], 'count' => $atts['num']));
31
 
32
     foreach($tweets as $favs) {
33
 
34
       /* The URLs (if any) */
35
       $tweeturl = $tweeturl = $favs->entities->urls['0']->expanded_url;;
36
       $tcourl = $favs->entities->urls['0']->url;
37
 
38
       $return .= '<div style="width: 60px; vertical-align:top;"><img src="' . $favs->user->profile_image_url . '" width="48" height="48" style="float: left;"></div>';
39
       $return .= '<div style="margin-left: 72px;"><strong>' . $favs->user->name . '</strong> (<a href="http://twitter.com/' . $favs->user->screen_name . '" target="_blank">@' . $favs->user->screen_name . '</a>) - ' . beliefmedia_twitterlike_links($favs->text) . '';
40
       if ($tweeturl != '') $return .= '<small>URL: <a href="' . $tcourl . '" title="' . $tweeturl . '">' . beliefmedia_truncate_twitterlike_url($tweeturl) . '</a></small>';
41
       $return .= '<strong>Posted:</strong> ' . beliefmedia_twitter_time($favs->created_at) . '</div>';
42
       $return .= '
43
<p style="clear:both; height: 3px;">';
44
 
45
     }
46
 
47
  set_transient($transient, $return, $atts['cache']);
48
  return $return;
49
 }
50
}
51
add_shortcode('twitterlikes', 'beliefmedia_twitter_likes');
52
 
53
/*
54
 Retrieve Twitter Favorites (Likes) and Display in WordPress with Shortcode
55
 http://www.beliefmedia.com/twitter-likes
56
*/
57
 
58
function beliefmedia_twitter_time($time) {
59
  $newtime = date(('F j, Y, g:i a'), strtotime($time));
60
 return $newtime;
61
}
62
 
63
function beliefmedia_twitterlike_links($text) {
64
  $text = preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Z()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text);
65
  $text = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '<a href="http://twitter.com/search?q=$1" target="_blank" rel="noopener noreferrer">#$1</a>', $text);
66
  $text = preg_replace('#@([\\d\\w]+)#', '<a href="http://twitter.com/$1" target="_blank" rel="noopener noreferrer">$0</a>', $text);
67
 return $text;
68
}
69
 
70
function beliefmedia_truncate_twitterlike_url($string, $maxcharacters = '35') {
71
 $textLength = strlen($string);
72
  if ($textLength > $maxcharacters) return substr_replace($string, '...', $maxcharacters/2, $textLength-$maxcharacters);
73
    else return $string;
74
}

The first function will convert the returned Twitter time into a more sensible format. Adjust as necessary by reference to PHP's date() function.

The second function converts text hashtags, username mentions, and URLs, into clickable links.

The last function takes a URL and snips it into two halves. We do this simply to preserve space. Alter the 35 to a maximum URL length.

Shortcode Attributes

The following shortcode attributes are available.

user

The twitteruser is the user for which to retrieve likes.

num

Specifies the number of records to retrieve. Must be less than or equal to 200. Specify the default in your shortcode function.

cache

The cache is the amount of time to cache the data locally before making another request. Twitter rate limits the number of requests to a maximum to 15 per 15 minute window which is more than enough for personal use. Since favorites don't change that often, and the request takes a little bit of time, we suggest caching data for 12 hours. Alter this in the shortcode function (or your post shortcode) if required.

PHP Function

Used outside of WordPress, the following may be used.

1
<?php 
2
require '/home/path/public_html/to/twitteroauth/autoload.php';
3
use Abraham\TwitterOAuth\TwitterOAuth;
4
include('../simple-cache/cache.inc.php');
5
 
6
/*
7
 Retrieve Twitter Favorites (Likes) and Display in WordPress with Shortcode
8
 http://www.beliefmedia.com/twitter-likes
9
*/
10
 
11
function beliefmedia_twitter_likes($args = '') {
12
 
13
  $atts = array(
14
    'user' => 'MartyKhoury',
15
    'num' => '20',
16
    'consumerkey' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
17
    'consumersecret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
18
    'accesstoken' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
19
    'accesstokensecret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
20
    'cache' => 3600 * 24 * 7
21
  );
22
 
23
 /* Ensure Simple Cache functions available */
24
 if (!function_exists('beliefmedia_get_transient')) return 'Simple Cache Required';
25
 
26
 /* Merge $args with $atts */
27
 $atts = ($args == '') ? $atts : array_merge($atts, $args);
28
 
29
 $transient = 'bm_twitterlikes_' . md5(serialize($atts));
30
 $cached =  beliefmedia_get_transient($transient, $atts['cache']);
31
 
32
 if ($cached !== false ) {
33
  return $cached;
34
 
35
  } else {
36
 
37
    $consumerkey = $atts['consumerkey'];
38
    $consumersecret = $atts['consumersecret'];
39
    $accesstoken = $atts['accesstoken'];
40
    $accesstokensecret = $atts['accesstokensecret'];
41
 
42
    $connection = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
43
    $tweets = $connection->get('favorites/list', array('screen_name' => $atts['user'], 'count' => $atts['num']));
44
 
45
     foreach($tweets as $favs) {
46
 
47
       /* The URLs (if any) */
48
       $tweeturl = $tweeturl = $favs->entities->urls['0']->expanded_url;
49
       $tcourl = $favs->entities->urls['0']->url;
50
 
51
       $return .= '<div style="width: 60px; vertical-align:top;"><img src="' . $favs->user->profile_image_url . '" width="48" height="48" style="float: left;"></div>';
52
       $return .= '<div style="margin-left: 72px;"><strong>' . $favs->user->name . '</strong> (<a href="http://twitter.com/' . $favs->user->screen_name . '" target="_blank">@' . $favs->user->screen_name . '</a>) - ' . beliefmedia_twitterlike_links($favs->text) . '';
53
       if ($tweeturl != '') $return .= '<small>URL: <a href="' . $tcourl . '" title="' . $tweeturl . '">' . beliefmedia_truncate_twitterlike_url($tweeturl) . '</a></small>';
54
       $return .= '<strong>Posted:</strong> ' . beliefmedia_twitter_time($favs->created_at) . '</div>';
55
       $return .= '
56
<p style="clear:both; height: 3px;">';
57
 
58
     }
59
 
60
  beliefmedia_set_transient($transient, $return);
61
  return $return;
62
 }
63
}
1
<?php 
2
/*
3
 Retrieve Twitter Favorites (Likes) and Display in WordPress with Shortcode
4
 http://www.beliefmedia.com/twitter-likes
5
*/
6
 
7
function beliefmedia_twitter_time($time) {
8
  $newtime = date(('F j, Y, g:i a'), strtotime($time));
9
 return $newtime;
10
}
11
 
12
function beliefmedia_twitterlike_links($text) {
13
  $text = preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Z()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text);
14
  $text = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '<a href="http://twitter.com/search?q=$1" target="_blank" rel="noopener noreferrer">#$1</a>', $text);
15
  $text = preg_replace('#@([\\d\\w]+)#', '<a href="http://twitter.com/$1" target="_blank" rel="noopener noreferrer">$0</a>', $text);
16
 return $text;
17
}
18
 
19
function beliefmedia_truncate_twitterlike_url($string, $maxcharacters = '35') {
20
 $textLength = strlen($string);
21
  if ($textLength > $maxcharacters) return substr_replace($string, '...', $maxcharacters/2, $textLength-$maxcharacters);
22
    else return $string;
23
}

Usage is as follows:

1
/* Usage */
2
// echo beliefmedia_twitter_likes();
3
 
4
/* Usage with arguments */
5
$args = array('num' => '5', 'cache' => '3600');
6
echo beliefmedia_twitter_likes($args);

A request for favorites is limited to your own account.

Considerations

  • Liking articles, from Twitter .
  • More information on the GET favorites/list endpoint can be found here . There are a number of other attributes that could be applied but we'll reserve that functionality for our naked PHP function. The purpose of the shortcode was to make accessing data easy.

Download

Twitteroauth can be downloaded from Github , or via the source menu on the library website .


Title: Display Twitter Favorites in WordPress or with PHP
Description: Retrieve Twitter Favorites (Likes) and Display in WordPress with Shortcode, or with PHP.
  Download • Version 0.2, 1.4K, zip, Category: WordPress Shortcodes
PHP Code & Snippets, (1.5K)    

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

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment