I need help with my code. What it's suppose to do is a user enter the full URL from twitter into a text field ('https://twitter.com/openbayou/status/1487977976033685506') and when the post is saved, it breaks down the url by using explode
and then gets data from a tweet via Twitter API v2.
My code:
$tweet_url_raw = get_field('twitter_url');
$parts = explode('/', $tweet_url_raw);
$url = 'https://api.twitter.com/2/tweets/' . $parts[5] . '?expansions=author_id&tweet.fields=created_at&user.fields=username,verified';
$authorization = 'Authorization: Bearer ' . get_field_object('twitter_bearer_token', 'option')['value'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
$tweet_data = json_encode($result);
$tweet_data2 = json_decode($tweet_data);
The code above does get the data:
{"data":{"text":"SEC Super Bowl!!","created_at":"2022-01-31T02:36:09.000Z","author_id":"1471331","id":"1487977976033685506"},"includes":{"users":[{"name":"OpenBayou","verified":false,"id":"1471331","username":"openbayou"}]}}
The problem I'm having is when I'm trying to get individual data from the output. I'm trying to update a text field called tweet
with the text from text
. I've tried to use update_field('tweet', $tweet_data2->data, $post_id);
and it was blank. When I use update_field('tweet2', $tweet_data2["data"], $post_id);
all it saves is {
Any idea what I'm doing wrong?
CodePudding user response:
You are almost there.
Since you omitted the associative
parameter for json_decode
, it defaults to false
so you get an object, not an array. You then need to reference it as such:
$tweet_data2 = json_decode($tweet_data);
echo 'Tweet text: ' . $tweet_data2->data->text;
If you prefer to work with arrays, simply pass true
to json_decode
:
$tweet_data2 = json_decode($tweet_data, true);
echo 'Tweet text: ' . $tweet_data2['data']['text'];
More info on json_decode
can be found at the PHP Manual site:
https://www.php.net/manual/en/function.json-decode.php