Search code examples
twitter-oauthwordpress-shortcodetwitter-api-v2

Need help updating Abraham Twitteroauth v2 GET Feed


I created a WordPress plugin using Abraham TwitterOAuth v1.1 and now I am trying to update it to v2 but getting lost in the Docs on how to implement the changes for TwitterOAuth. Here is my v1.1 code with a few changes to hide my credentials:

function my_twitter_feed_shortcode() {  
   
    
    // Twitter API credentials
    $consumer_key = 'XXXXXX';
    $consumer_secret = 'XXXXXX';
    $access_token = 'XXXXXX';
    $access_token_secret = 'XXXXXX';

    // Create a TwitterOAuth instance
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);  

    // Fetch tweets using the API
    $tweets = $connection->get('statuses/user_timeline', ['screen_name' => 'XXXXXX', 'count' => 10]);
   
    // Generate HTML markup for the tweets
    $html = '<ul>';
    foreach ($tweets as $tweet) {
        $html .= '<li>' . $tweet->text . '</li>';
    }
    $html .= '</ul>';

    // Return the generated HTML
    return $html;

}
add_shortcode('my_twitter_feed', 'my_twitter_feed_shortcode');

So after updating for v2 $connection->setApiVersion('2'); fetching the tweets no longer works. I also updated the code to try and use the demo v2 code and test my results: $tweets = $connection->get('users', ['ids' => ######]); so the updated code is now:

function stride_twitter_feed_shortcode() {  
   
    
    // Twitter API credentials
    $consumer_key = 'XXXXXX';
    $consumer_secret = 'XXXXXX';
    $access_token = 'XXXXXX';
    $access_token_secret = 'XXXXXX';

    // Create a TwitterOAuth instance
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);

    // Set API Version 2
    $connection->setApiVersion('2');

    // Fetch tweets using the API
    $tweets = $connection->get('users', ['ids' => ######]);    
   
    // Generate HTML markup for the tweets
    $html = '<ul>';
    foreach ($tweets as $tweet) {
        $html .= '<li>' . $tweet->text . '</li>';
    }
    $html .= '</ul>';

    // Return the generated HTML
    return $html;

}
add_shortcode('stride_twitter_feed', 'stride_twitter_feed_shortcode');

While this returns the ID, Name, & Username when debugging (doesn't return anything to the screen so still have to figure that part out) I am not sure how to show the timeline like in v1.1. The updated Timeline endpoint in the Docs say v2 is: /2/users/:id/tweets but how do I get that working in TwitterOAuth? Tried a few different things with no luck, so any help would be great.

UPDATE: Updated code thanks to @andytela, I also added a few things. Added the ability to let twitter generate my ID instead, just update twitter_name. I also am filtering out replies, showing retweets with their name, handle, avatar. Also I only need 3 results so I used foreach ($tweets->data as $index => $tweet) { to get the index of each tweet and then at the end I used this to stop once it reached the 3rd one (array index 2):

if ($index === 2) {
    break;
}

Here is my full plugin code:

require_once( plugin_dir_path( __FILE__ ) . 'vendor/autoload.php');
use Abraham\TwitterOAuth\TwitterOAuth;

function my_twitter_feed_shortcode() {     
    
    // Twitter API credentials
    $consumer_key = 'XXXXXX';
    $consumer_secret = 'XXXXXX';
    $access_token = 'XXXXXX';
    $access_token_secret = 'XXXXXX';
    $bearer_token = 'XXXXXX';

    // Create a TwitterOAuth instance
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret, $bearer_token);

    $connection->setApiVersion('2');

    // Fetch tweets using the API   
    $response = $connection->get('users/by/username/twitter_name');
    $user_id = $response->data->id;
    
    $tweets = $connection->get(
        "users/$user_id/tweets",
        [
            'max_results' => 5,
            'tweet.fields' => 'created_at,author_id,public_metrics,referenced_tweets',
            'expansions' => 'attachments.media_keys,author_id,referenced_tweets.id,referenced_tweets.id.author_id',
            'media.fields' => 'url,public_metrics,organic_metrics',
            'user.fields' => 'public_metrics,profile_image_url,verified',
            'exclude' => 'replies',
        ]
    );

    // Generate HTML markup for the tweets
    $html = '<div class="twitter_wrap">';
    foreach ($tweets->data as $index => $tweet) {        
        $tweetText = urlencode($tweet->text);
        $shareUrl = 'https://twitter.com/intent/tweet?text=' . $tweetText;
        $tweetDate = date('M j, Y', strtotime($tweet->created_at));
        $tweetTime = date('h:i A', strtotime($tweet->created_at));
        $authorId = $tweet->author_id;
        
        $author = $tweets->includes->users[array_search($authorId, array_column($tweets->includes->users, 'id'))];
        $authorName = $author->name;
        $authorHandle = $author->username;        
        $authorAvatar = $author->profile_image_url;
        $authorVerified = $author->verified;

        
        // Check if the tweet is a retweet
        if (isset($tweet->referenced_tweets) && !empty($tweet->referenced_tweets)) {
            $retweetedTweetId = $tweet->referenced_tweets[0]->id;
            foreach ($tweets->includes->tweets as $retweetedTweet) {
                if ($retweetedTweet->id === $retweetedTweetId) {
                    $retweetedAuthorId = $retweetedTweet->author_id;
                    foreach ($tweets->includes->users as $retweetedAuthor) {
                        if ($retweetedAuthor->id === $retweetedAuthorId) {
                            // Assign retweeted author information
                            $authorName = $retweetedAuthor->name;
                            $authorHandle = $retweetedAuthor->username;
                            $authorAvatar = $retweetedAuthor->profile_image_url;
                            $authorVerified  = $retweetedAuthor->verified;
        
                            // Use retweeted tweet's date and time
                            $tweetDate = date('M j, Y', strtotime($retweetedTweet->created_at));
                            $tweetTime = date('h:i A', strtotime($retweetedTweet->created_at));
        
                            // Update the current tweet to the retweeted tweet
                            $tweet = $retweetedTweet;
                            break;
                        }
                    }
                    break;
                }
            }
        }

        $html .= '
        <div class="twitter_item_wrap">
            <div class="user_row">
                <div class="user_avatar_wrap">
                    <div class="avatar"><img src="' . $authorAvatar . '" alt="Avatar"></div>
                    <div class="user_wrap"> 
                        <div class="name">' . $authorName . ' ' . ( $authorVerified ? '<i class="verified_icon"></i>' : '' ) . '</div>
                        <div class="handle">@' . $authorHandle . '</div>
                    </div>
                </div>
                <i class="twitter_icon"></i>
            </div>
            <div class="text">' . $tweet->text . '</div>
            <div class="time_date">' . $tweetTime . ' &bull; ' . $tweetDate . '</div>
            <div class="links_wrap">
                <div class="reply">
                    <a href="https://twitter.com/intent/tweet?in_reply_to=' . $tweet->id . '">
                        <i></i>
                        ' . $tweet->public_metrics->reply_count . '
                        <span class="tooltip">Reply</span>
                    </a>
                </div>
                <div class="retweet">
                    <a href="https://twitter.com/intent/retweet?tweet_id=' . $tweet->id . '">
                        <i></i>
                        ' . $tweet->public_metrics->retweet_count . '
                        <span class="tooltip">Retweet</span>
                    </a>
                </div>
                <div class="favorite">
                    <a href="https://twitter.com/intent/like?tweet_id=' . $tweet->id . '">
                        <i></i>
                        ' . $tweet->public_metrics->like_count . '
                        <span class="tooltip">Like</span>
                    </a>
                </div>
                <div class="share">
                    <a href="' . $shareUrl . '">
                        <i></i>
                        <span class="tooltip">Share</span>
                    </a>
                </div>
            </div>
        </div>';

        if ($index === 2) {
            break;
        }       
    }
    $html .= '</div>';    

    // Return the generated HTML
    return $html;

}
add_shortcode('my_twitter_feed', 'my_twitter_feed_shortcode');

Solution

  • Change this line

    $tweets = $connection->get('users', ['ids' => ######]); 
    

    To this

    $tweets = $connection->get("users/######/tweets" );
    

    Worked for me

    Then just change the loop to this

     foreach ($tweets->data as $tweet) {
    

    To get the tweets out