wp_remote_retrieve_body() WP 2.7.0
Получает только тело (контент) ответа, который был получен с помощью любой из функций типа wp_remote_*, например wp_remote_get().
Эта функция принимает только один параметр, ответ от любой из функций wp_remote_*
, например wp_remote_get().
Чтобы получить только код ответа (например 200), используйте функцию wp_remote_retrieve_response_code().
Хуков нет.
Возвращает
Строку. Тело ответа (контент) в виде строки или пустую строку, если ответ пустой или неправильно передан параметр.
Использование
wp_remote_retrieve_body( $response );
- $response(массив) (обязательный)
- Ответ полученный с помощью одной из функций WP HTTP API, например: wp_remote_get().
Примеры
#1 Получение тела ответа
Получим данные пользователя Github:
$response = wp_remote_get( 'https://api.github.com/users/doiftrue' ); $body = wp_remote_retrieve_body( $response ); echo $body; /* выведет: { "login":"doiftrue", "id":15121552, "avatar_url":"https://avatars.githubusercontent.com/u/15121552?v=3", "gravatar_id":"", "url":"https://api.github.com/users/doiftrue", "html_url":"https://github.com/doiftrue", "followers_url":"https://api.github.com/users/doiftrue/followers", "following_url":"https://api.github.com/users/doiftrue/following{/other_user}", "gists_url":"https://api.github.com/users/doiftrue/gists{/gist_id}", "starred_url":"https://api.github.com/users/doiftrue/starred{/owner}{/repo}", "subscriptions_url":"https://api.github.com/users/doiftrue/subscriptions", "organizations_url":"https://api.github.com/users/doiftrue/orgs", "repos_url":"https://api.github.com/users/doiftrue/repos", "events_url":"https://api.github.com/users/doiftrue/events{/privacy}", "received_events_url":"https://api.github.com/users/doiftrue/received_events", "type":"User", "site_admin":false, "name":null, "company":null, "blog":null, "location":null, "email":null, "hireable":null, "bio":null, "public_repos":0, "public_gists":1, "followers":0, "following":0, "created_at":"2015-10-14T08:52:55Z", "updated_at":"2015-11-25T23:14:16Z" } */
#2 Получение удаленной страницы и её кэширование
function get_remote_html( $url, $trans_name = 'foo_remote_html' ) { // Проверим транзитную опцию, если её нет получим удаленных HTML if( false === ( $html = get_transient($trans_name) ) ){ // Получаем HTML $response = wp_remote_get( $url ); // Проверим на ошибки if ( is_wp_error( $response ) ) { return; } // Получим тело $html = wp_remote_retrieve_body( $response ); // Запишем полученный запрос в транзитную опцию на 24 часа set_transient( $trans_name, $html, 24 * HOUR_IN_SECONDS ); } return $html; } // вызываем функцию $html = get_remote_html('http://example.com/some-remote-file.html', 'my_trans_name');
Список изменений
С версии 2.7.0 | Введена. |
Код wp_remote_retrieve_body() wp remote retrieve body WP 5.6.2
function wp_remote_retrieve_body( $response ) {
if ( is_wp_error( $response ) || ! isset( $response['body'] ) ) {
return '';
}
return $response['body'];
}