英文:
Need help updating Abraham Twitteroauth v2 GET Feed
问题
我使用Abraham TwitterOAuth v1.1创建了一个WordPress插件,现在我正在尝试将其更新到v2,但在文档中如何实现对TwitterOAuth的更改方面感到困惑。以下是我的v1.1代码,其中有一些更改以隐藏我的凭据:
function my_twitter_feed_shortcode() {
// Twitter API凭据
$consumer_key = 'XXXXXX';
$consumer_secret = 'XXXXXX';
$access_token = 'XXXXXX';
$access_token_secret = 'XXXXXX';
// 创建TwitterOAuth实例
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
// 使用API获取推文
$tweets = $connection->get('statuses/user_timeline', ['screen_name' => 'XXXXXX', 'count' => 10]);
// 为推文生成HTML标记
$html = '<ul>';
foreach ($tweets as $tweet) {
$html .= '<li>' . $tweet->text . '</li>';
}
$html .= '</ul>';
// 返回生成的HTML
return $html;
}
add_shortcode('my_twitter_feed', 'my_twitter_feed_shortcode');
因此,在更新为v2后,$connection->setApiVersion('2');
获取推文不再起作用。我还更新了代码以尝试使用演示v2代码并测试我的结果:$tweets = $connection->get('users', ['ids' => ######]);
,所以更新后的代码现在是:
function stride_twitter_feed_shortcode() {
// Twitter API凭据
$consumer_key = 'XXXXXX';
$consumer_secret = 'XXXXXX';
$access_token = 'XXXXXX';
$access_token_secret = 'XXXXXX';
// 创建TwitterOAuth实例
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
// 设置API版本为2
$connection->setApiVersion('2');
// 使用API获取推文
$tweets = $connection->get('users', ['ids' => ######]);
// 为推文生成HTML标记
$html = '<ul>';
foreach ($tweets as $tweet) {
$html .= '<li>' . $tweet->text . '</li>';
}
$html .= '</ul>';
// 返回生成的HTML
return $html;
}
add_shortcode('stride_twitter_feed', 'stride_twitter_feed_shortcode');
虽然在调试时返回了ID、名称和用户名(不会在屏幕上返回任何内容,所以仍然需要弄清楚这一部分),但我不确定如何像v1.1中那样显示时间线。文档中更新的时间线终点说v2是:/2/users/:id/tweets
,但如何在TwitterOAuth中使其工作我尝试了一些不同的方法,但都没有成功,所以任何帮助都会很好。
更新: 感谢@andytela的代码更新,我还添加了一些内容。添加了让Twitter生成我的ID的功能,只需更新twitter_name
。我还过滤了回复,显示了带有其名称、句柄、头像的转推。此外,我只需要3个结果,所以我使用了foreach ($tweets->data as $index => $tweet) {
来获取每个推文的索引,然后在最后使用了这个来在达到第3个之后停止(数组索引2):
if ($index === 2) {
break;
}
以下是我的完整插件代码:
require_once( plugin_dir_path( __FILE__ ) . 'vendor/autoload.php');
use Abraham\TwitterOAuth\TwitterOAuth;
function my_twitter_feed_shortcode() {
// Twitter API凭据
$consumer_key = 'XXXXXX';
$consumer_secret = 'XXXXXX';
$access_token = 'XXXXXX';
$access_token_secret = 'XXXXXX';
$bearer_token = 'XXXXXX';
// 创建TwitterOAuth实例
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret, $bearer_token);
$connection->setApiVersion('2');
// 使用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',
]
);
// 为推文生成HTML标记
$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;
// 检查推文是否为转推
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) {
// 分配转推作者信息
$authorName = $retweetedAuthor->name;
$authorHandle = $retweetedAuthor->username;
$authorAvatar = $retweetedAuthor
<details>
<summary>英文:</summary>
I created a WordPress plugin using [Abraham TwitterOAuth](https://github.com/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');
</details>
# 答案1
**得分**: 1
将这一行更改为:
```php
$tweets = $connection->get("users/######/tweets" );
然后只需将循环更改为:
foreach ($tweets->data as $tweet) {
以获取推文。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论