建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

WordPress程序远程数据请求函数:wp_remote_post、wp_remote_get

GG网络技术分享 2025-03-18 16:12 0


发起 HTTP 请求,是再平常不过的需求了。一般的就是使用 file_get_contents 或者 cURL。

但是在WordPress中,使用 file_get_contents 或者 cURL 开发的主题或插件,都会被WordPress官方拒绝。因为,WordPress官方已经提供了封装好的 HTTP 请求函数。之前也曾简单介绍过:WordPress 使用wp_remote_get和wp_remote_post 替代curl。

wp_remote_get 发起GET请求

使用举例:

$response = wp_remote_get( 'https://数据网址' );
if ( is_array( $response ) && ! is_wp_error( $response ) && $response['response']['code'] == '200' ) {
$headers = $response['headers']; // array of http header lines
$body = $response['body']; // use the content
}

在获取到 $body 后,要根据实际情况,对其进行解析。

wp_remote_post发起POST请求

函数 wo_remote_post 返回的结果(wp_remote_get的结果也一样)如下:

  • 'headers' (string[]) 响应头信息。
  • 'body' (string) 响应体。
  • 'response' (array) HTTP 相关的相应数据。
  • 'code' (int|false) HTTP CODE。
  • 'message' (string|false) HTTP 相应消息。
  • 'cookies' (WP_HTTP_Cookie[]) cookies 信息。
  • 'http_response' (WP_HTTP_Requests_Response|null) 原始的 HTTP 相应。

使用举例:

$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array(
'username' => 'bob',
'password' => '1234xyz'
),
'cookies' => array()
)
);

if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}

标签: WordPress 教程

提交需求或反馈

Demand feedback