Skip to Content

twitter_cache()

Generate a Twitter feed for a user or a list (can be called by AJAX).

PHP February 14, 2018

Usage

PHP
nebula()->twitter_cache($username, $listname, $number_tweets, $include_retweets)

Parameters

$username
(Required) (String) The username to pull the feed of
Default: Great_Blakes

$listname
(Optional) (String) If using a list, the name of the list
Default: None

$numbertweets
(Optional) (Integer) The number of Tweets to get
Default: 5

$includeretweets
(Optional) (Boolean) Whether to include retweets
Default: true

Parameter Notes

This function requires a Twitter Bearer Token to be generated and set in Nebula Options!

If calling this function by AJAX, the data object should use the parameter names without the “$”.

Request or provide clarification »

Examples

Get the full tweet with clickable usernames, hashtags, and URLs.

PHP
<?php
    $tweets = nebula()->twitter_cache('Great_Blakes');
    echo $tweet->markup;    //This key is added by Nebula
?>

Demo


Example 1 (PHP)
Retrieve tweets with only PHP
NASA
We're partnering with industry to collect resources from the Moon, to help prepare the way for a sustainable human presence there under the #Artemis program. Tune in on Thurs., Dec. 3 at 1pm ET for an announcement of the companies selected: https://t.co/E81SWLhIU1 https://t.co/YQtCrCysLA
NASA
To an astronaut far from home, teamwork is as essential as oxygen and fuel. THIS Thursday, kids will have the opportunity to hear from @AstroVicGlover live from the @Space_Station about this very topic. Learn more about the event hosted by @AirAndSpace: https://t.co/EeA1GKldKR https://t.co/5aCRYcRGZ9
NASA
"I don't think people appreciate the vastness and the scope and the power of Nature, and the nature of storms." 🎧 Dive into the study of intense storms with @NASAEarth scientists on the latest @NASAJPL "On a Mission" podcast. Listen & subscribe: https://t.co/eHI10EK5mk https://t.co/whezXXk1vt

Example 2 (JS)
Fill pre-existing HTML with tweet data. This is good for displaying a single, latest tweet.

Example 3 (JS)
Generate the markup within a UL to display tweets. This method is good for showing multiple tweets.

    Example 4 (WordPress)
    Call the Nebula - Twitter Tweet widget

    We're partnering with industry to collect resources from the Moon, to help prepare the way for a sustainable human presence there under the #Artemis program. Tune in on Thurs., Dec. 3 at 1pm ET for an announcement of the companies selected: https://t.co/E81SWLhIU1 https://t.co/YQtCrCysLA
    4 hours ago

    To an astronaut far from home, teamwork is as essential as oxygen and fuel. THIS Thursday, kids will have the opportunity to hear from @AstroVicGlover live from the @Space_Station about this very topic. Learn more about the event hosted by @AirAndSpace: https://t.co/EeA1GKldKR https://t.co/5aCRYcRGZ9
    5 hours ago

    "I don't think people appreciate the vastness and the scope and the power of Nature, and the nature of storms." 🎧 Dive into the study of intense storms with @NASAEarth scientists on the latest @NASAJPL "On a Mission" podcast. Listen & subscribe: https://t.co/eHI10EK5mk https://t.co/whezXXk1vt
    6 hours ago

    Additional Notes

    This function can be called as a PHP function or via JavaScript using AJAX.

    Nebula adds a markup key to the Twitter object where it wraps detected strings in HTML tags (such as usernames, hashtags, and URLs in <a> tags).

    The Nebula – Twitter Tweets widget uses this function.

    Source File

    Located in /libs/Functions.php on line 2149.

    1 Hook

    Find these filters and actions in the source code below to hook into them. Use do_action() and add_filter() in your functions file or plugin.

    Filters
    "nebula_twitter_cache_defaults"
    Need a new filter hook? Request one here.

    Actions
    This function has no action hooks available. Request one?

    PHP
        public function twitter_cache($options=array()){
            $defaults = apply_filters('nebula_twitter_cache_defaults', array(
                'user' => 'Great_Blakes',
                'list' => null,
                'number' => 5,
                'retweets' => 1,
            ));
    
            $data = array_merge($defaults, $options);
    
            if ( !empty($_POST['data']) ){
                if ( !wp_verify_nonce($_POST['nonce'], 'nebula_ajax_nonce') ){ die('Permission Denied.'); }
                $data['user'] = ( isset($_POST['data']['user']) )? sanitize_text_field($_POST['data']['user']) : $defaults['user'];
                $data['list'] = ( isset($_POST['data']['list']) )? sanitize_text_field($_POST['data']['list']) : $defaults['list']; //Only used for list feeds
                $data['number'] = ( isset($_POST['data']['number']) )? sanitize_text_field($_POST['data']['number']) : $defaults['number'];
                $data['retweets'] = ( isset($_POST['data']['retweets']) )? sanitize_text_field($_POST['data']['retweets']) : $defaults['retweets']; //1: Yes, 0: No
            }
    
            $twitter_timing_id = $this->timer('Twitter Cache (' . $data['user'] . ')', 'start', 'Twitter Cache');
    
            error_reporting(0); //Prevent PHP errors from being cached.
    
            if ( !empty($data['list']) ){
                $feed = 'https://api.twitter.com/1.1/lists/statuses.json?slug=' . $data['list'] . '&owner_screen_name=' . $data['user'] . '&count=' . $data['number'] . '&include_rts=' . $data['retweets'] . '&tweet_mode=extended';
            } else {
                $feed = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $data['user'] . '&count=' . $data['number'] . '&include_rts=' . $data['retweets'] . '&tweet_mode=extended';
            }
    
            $bearer = $this->get_option('twitter_bearer_token', '');
            if ( empty($bearer) ){
                trigger_error('A Twitter bearer token is required to get tweets', E_USER_WARNING);
    
                if ( !empty($_POST['data']) ){
                    echo false;
                    wp_die();
                } else {
                    return false;
                }
            }
    
            $tweets = get_transient('nebula_twitter_' . $data['user']);
            if ( empty($tweets) || !empty($tweets->error) || $this->is_debug() ){
                $args = array('headers' => array('Authorization' => 'Bearer ' . $bearer));
    
                $response = $this->remote_get($feed, $args);
                if ( is_wp_error($response) ){
                    return false;
                }
    
                $tweets = json_decode($response['body']);
    
                //If there are no tweets -or- if an error is return (for example if an account does not exist)
                if ( empty($tweets) || !empty($tweets->error) ){
                    trigger_error('No tweets were retrieved. Verify all options are correct, the requested Twitter account exists, and that an active bearer token is being used.', E_USER_NOTICE);
    
                    if ( !empty($_POST['data']) ){
                        echo false;
                        wp_die();
                    } else {
                        return false;
                    }
                }
    
                //Add convenient data to the tweet object
                foreach ( $tweets as $tweet ){
                    $tweet->tweet_url = 'http://twitter.com/' . $tweet->user->screen_name . '/status/' . $tweet->id; //Add Tweet URL
    
                    //Convert times
                    $tweet->time_ago = human_time_diff(strtotime($tweet->created_at)); //Relative time
                    $tweet->time_formatted = date('l, F j, Y \a\t g:ia', strtotime($tweet->created_at)); //Human readable time
                    $tweet->time_ago_raw = date('U')-strtotime($tweet->created_at);
    
                    //Convert usernames, hashtags, and URLs into clickable links and add other markup
                    $tweet->markup = preg_replace(array(
                        "/(http\S+)/i", //URLs (must be first)
                        "/@([a-z0-9_]+)/i", //Usernames
                        "/#([a-z0-9_]+)/i", //Hashtags
                        "/(\d+\/(\d+)?)$/i", //Series numbers
                    ), array(
                        "<a class='tweet-embedded-link' href='$1' target='_blank' rel='noopener'>$1</a>",
                        "<a class='tweet-embedded-username' href='https://twitter.com/$1' target='_blank' rel='noopener'>@$1</a>",
                        "<a class='tweet-embedded-hashtag' href='https://twitter.com/hashtag/$1' target='_blank' rel='noopener'>#$1</a>",
                        "<small class='tweet-embedded-series-number'>$1</small>",
                    ), trim($tweet->full_text));
                }
    
                set_transient('nebula_twitter_' . $data['user'], $tweets, MINUTE_IN_SECONDS*5); //5 minute expiration
            }
    
            $this->timer($twitter_timing_id, 'end');
    
            if ( !empty($_POST['data']) ){
                echo json_encode($tweets);
                wp_die();
            } else {
                return $tweets;
            }
        }
    

    Override

    This function can not be short-circuited with an override filter. Request one?