通用API文档

发起 HTTP 请求

💡 云策文档标注

概述

本文档介绍如何在 WordPress 主题或插件中发起 HTTP 请求,例如从外部 API 获取数据,并利用 WordPress 提供的辅助函数简化操作。

关键要点

  • WordPress 提供了多种辅助函数来发起 HTTP 请求,如 wp_remote_get()、wp_remote_post()、wp_remote_head() 和 wp_remote_request()。
  • 响应处理函数包括 wp_remote_retrieve_body()、wp_remote_retrieve_header()、wp_remote_retrieve_headers()、wp_remote_retrieve_response_code() 和 wp_remote_retrieve_response_message(),用于提取响应中的不同部分。
  • 文档后续将详细讲解 GET、POST、性能、高级功能和认证等主题。

代码示例

$response = wp_remote_get( 'https://api.github.com/users/wordpress' );
$body     = wp_remote_retrieve_body( $response );

📄 原文内容

Very often we need to make HTTP requests from our theme or plugin, for example when we need to fetch data from an external API. Luckily WordPress has many helper functions to help you do that.

In this section, you will learn how to properly make HTTP requests and handle their responses.

Here’s an example of what you’re going to see

$response = wp_remote_get( 'https://api.github.com/users/wordpress' );
$body     = wp_remote_retrieve_body( $response );

In the next articles you’ll see a detailed explanation on how to make the requests:

If you’re just looking for the available helper functions, here they are:

The functions below are the ones you will use to retrieve a URL.

The other helper functions deal with retrieving different parts of the response. These make usage of the API very simple and are the preferred method for processing response objects.

  • <a href="https://developer.wordpress.org/reference/functions/wp_remote_retrieve_body/">wp_remote_retrieve_body()</a> – Retrieves just the body from the response.
  • <a href="https://developer.wordpress.org/reference/functions/wp_remote_retrieve_header/">wp_remote_retrieve_header()</a> – Retrieve a single header by name from the raw response.
  • <a href="https://developer.wordpress.org/reference/functions/wp_remote_retrieve_headers/">wp_remote_retrieve_headers()</a> – Retrieve only the headers from the raw response.
  • <a href="https://developer.wordpress.org/reference/functions/wp_remote_retrieve_response_code/">wp_remote_retrieve_response_code()</a> – Retrieve the response code for the HTTP response. This should be 200, but could be 4xx or even 3xx on failure.
  • <a href="https://developer.wordpress.org/reference/functions/wp_remote_retrieve_response_message/">wp_remote_retrieve_response_message()</a> – Retrieve only the response message from the raw response.