Не виводить тест из поста твитера через API, не могу понять в чём ошибка?

Ссылка скопирована
1 ответ

Вот код плагина который пишу для wordpress

<?php /**  * Plugin Name:   * Description:   * Version: 1.0  * Author:   */  // Add shortcode for displaying Twitter timeline function twitter_timeline_shortcode() {     // Your Twitter API credentials     $consumer_key = '00000';     $consumer_secret = '00000';     $oauth_access_token = '000000';     $oauth_access_token_secret = '000000';      // User whose tweets you want to display     $twitter_username = '@elonmusk';      // Include TwitterAPIExchange library     require_once plugin_dir_path(__FILE__) . 'TwitterAPIExchange.php';      // Set up API request parameters     $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';     $request_method = 'GET';     $get_field = '?screen_name=' . $twitter_username;      // Make API request using TwitterAPIExchange     $twitter = new TwitterAPIExchange(array(         'oauth_access_token' => $oauth_access_token,         'oauth_access_token_secret' => $oauth_access_token_secret,         'consumer_key' => $consumer_key,         'consumer_secret' => $consumer_secret     ));     $twitter_timeline = $twitter->setGetfield($get_field)                                 ->buildOauth($url, $request_method)                                 ->performRequest();      // Decode JSON response into an array     $twitter_timeline = json_decode($twitter_timeline);      // Output tweets as HTML     $output = '<div class="twitter-timeline">';     foreach ($twitter_timeline as $tweet) {         $output .= '<div class="twitter-tweet">';         $output .= '<p>' . $tweet->text . '</p>';         $output .= '<p class="twitter-date">' . date('F j, Y, g:i a', strtotime($tweet->created_at)) . '</p>';         var_dump($tweet);         $output .= '</div>';     }     $output .= '</div>';      return $output; }  add_shortcode('twitter-feed', 'twitter_timeline_shortcode'); ?>

<?php /** * Plugin Name: * Description: * Version: 1.0 * Author: */ // Add shortcode for displaying Twitter timeline function twitter_timeline_shortcode() { // Your Twitter API credentials $consumer_key = '00000'; $consumer_secret = '00000'; $oauth_access_token = '000000'; $oauth_access_token_secret = '000000'; // User whose tweets you want to display $twitter_username = '@elonmusk'; // Include TwitterAPIExchange library require_once plugin_dir_path(__FILE__) . 'TwitterAPIExchange.php'; // Set up API request parameters $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json'; $request_method = 'GET'; $get_field = '?screen_name=' . $twitter_username; // Make API request using TwitterAPIExchange $twitter = new TwitterAPIExchange(array( 'oauth_access_token' => $oauth_access_token, 'oauth_access_token_secret' => $oauth_access_token_secret, 'consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret )); $twitter_timeline = $twitter->setGetfield($get_field) ->buildOauth($url, $request_method) ->performRequest(); // Decode JSON response into an array $twitter_timeline = json_decode($twitter_timeline); // Output tweets as HTML $output = '<div class="twitter-timeline">'; foreach ($twitter_timeline as $tweet) { $output .= '<div class="twitter-tweet">'; $output .= '<p>' . $tweet->text . '</p>'; $output .= '<p class="twitter-date">' . date('F j, Y, g:i a', strtotime($tweet->created_at)) . '</p>'; var_dump($tweet); $output .= '</div>'; } $output .= '</div>'; return $output; } add_shortcode('twitter-feed', 'twitter_timeline_shortcode'); ?>

но на сайте при добавлении шорткода [twitter-feed] выдаёт ошибку
"Warning: Attempt to read property "text" on array in C:OpenServerdomainsmyuniversitywork.uawp-contentpluginsTwittMeTwittMe.php on line 46

Warning: Attempt to read property "created_at" on array in C:OpenServerdomainsmyuniversitywork.uawp-contentpluginsTwittMeTwittMe.php on line 47"

Дополнительно

Скорее всего тебе нужно обращаться таким образом, потому что твой JSON скорее всего лежит внутри массива

$tweet[0]->text  $tweet[0]->created_at

$tweet[0]->text $tweet[0]->created_at

Нужно решить такую задачу?

Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

Заказать помощь
Лучший ответ
1
Андрей PHP Ответ

По описанию похоже, что проблема не в WordPress как таковом, а в обработке ответа Twitter/X API. Если текст поста не выводится, сначала проверьте, что API реально возвращает поле с текстом. У X API v2 текст обычно находится в data.text, а не в произвольном поле, которое можно угадать по старым примерам.

Минимальная диагностика: временно выведите сырой ответ в лог, а не на страницу:

$response = wp_remote_get($url, [
    'headers' => [
        'Authorization' => 'Bearer ' . $bearer_token,
    ],
    'timeout' => 15,
]);
 
if (is_wp_error($response)) {
    error_log($response->get_error_message());
    return 'Ошибка запроса к Twitter API';
}
 
$body = wp_remote_retrieve_body($response);
error_log($body);
$data = json_decode($body, true);

$response = wp_remote_get($url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $bearer_token, ], 'timeout' => 15, ]); if (is_wp_error($response)) { error_log($response->get_error_message()); return 'Ошибка запроса к Twitter API'; } $body = wp_remote_retrieve_body($response); error_log($body); $data = json_decode($body, true);

Дальше проверяйте структуру:

if (! empty($data['data'])) {
    foreach ($data['data'] as $tweet) {
        echo '<p>' . esc_html($tweet['text'] ?? '') . '</p>';
    }
}

if (! empty($data['data'])) { foreach ($data['data'] as $tweet) { echo '<p>' . esc_html($tweet['text'] ?? '') . '</p>'; } }

Частые причины: используется старый endpoint API v1.1, нет Bearer Token, приложение не имеет нужного доступа, превышен лимит, JSON декодируется в объект, а код обращается как к массиву, или текст есть, но вы выводите не то поле. Ключи API не храните прямо в публичном коде плагина, лучше вынести в настройки или константы вне репозитория.

Также учитывайте, что X/Twitter часто возвращает не саму ошибку в HTTP 500, а нормальный JSON с полем errors или title. Поэтому проверяйте код ответа через wp_remote_retrieve_response_code(). Если код 401, проблема в токене; если 403, у приложения нет доступа; если 429, упёрлись в лимит. В шорткоде не выводите технические ошибки посетителям, лучше показывать нейтральное сообщение, а подробности писать в error_log.

Другие ответы (0)

Пока нет других ответов. Будьте первым, кто поможет автору.

Ответить на вопрос

комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Вам также может быть интересно