Skip to Content
Menu

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

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

    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.

    Was this page helpful? Yes No


      A feedback message is required to submit this form.


      Please check that you have entered a valid email address.

      Enter your email address if you would like a response.

      Thank you for your feedback!

      Source File

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

      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,
                  ));
      
                  $options = ( is_array($options) )? $options : array(); //Ensure the provided options is an array (and assign an empty array if it does not exist). Remember, this function may be called via WP hook.
      
                  $data = array_merge($defaults, $options);
                  $post = $this->super->post; //Get the $_POST data
      
                  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 = nebula()->transient('nebula_twitter_' . $data['user'], function($data){
                      $args = array('headers' => array('Authorization' => 'Bearer ' . $data['bearer']));
      
                      $response = $this->remote_get($data['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->errors) || !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($data['post']['data']) ){
                              echo false;
                              wp_die(); //Exit AJAX
                          } 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));
                      }
      
                      return $tweets;
                  }, array('bearer' => $bearer, 'feed' => $feed, 'post' => $post), MINUTE_IN_SECONDS*5);
      
                  $this->timer($twitter_timing_id, 'end');
      
                  if ( !empty($post['data']) ){
                      echo wp_json_encode($tweets);
                      wp_die();
                  } else {
                      return $tweets;
                  }
              }
      

      Override

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