当前位置:首页文章笔记建站教程WordPress程序远程数据请求函数:wp_remote_post、wp_remote_get

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

发起 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 请求

使用举例:

  1. $response = wp_remote_get( ‘https://数据网址’ );
  2. if ( is_array( $response ) && ! is_wp_error( $response ) && $response[‘response’][‘code’] == ‘200’ ) {
  3. $headers = $response[‘headers’]; // array of http header lines
  4. $body = $response[‘body’]; // use the content
  5. }

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

wp_remote_post 发起 POST 请求

  • ‘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 相应。

使用举例:

  1. $response = wp_remote_post( $url, array(
  2. ‘method’ => ‘POST’,
  3. ‘timeout’ => 45,
  4. ‘redirection’ => 5,
  5. ‘httpversion’ => ‘1.0’,
  6. ‘blocking’ => true,
  7. ‘headers’ => array(),
  8. ‘body’ => array(
  9. ‘username’ => ‘bob’,
  10. ‘password’ => ‘1234xyz’
  11. ),
  12. ‘cookies’ => array()
  13. )
  14. );
  15. if ( is_wp_error( $response ) ) {
  16. $error_message = $response->get_error_message();
  17. echo "Something went wrong: $error_message";
  18. } else {
  19. echo ‘Response:<pre>’;
  20. print_r( $response );
  21. echo

‘;
}

温馨提示:

文章标题:WordPress程序远程数据请求函数:wp_remote_post、wp_remote_get

文章链接:https://www.wuyanshuo.cn/1305.html

更新时间:2022年09月12日

本站资源均为两层压缩,第一层7z(后缀若为wys,请自行修改为7z)有解压密码;第二层zip或cbz,无解压密码,可直接使用漫画类软件程序查看;详情可参考解压教程

本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn我们将第一时间处理! 资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。 所有资源仅限于参考和学习,版权归原作者所有,更多请阅读无言说网络服务协议

给TA打赏
共{{data.count}}人
人已打赏
建站教程

WordPress如何基于最后发布文章的时间来排序作者用户列表

2022-9-12 19:58:18

建站教程

WordPress网站如何生成静态HTML网页

2022-9-12 23:02:05

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
'