WordPress Tutorial

WordPress program remote data request functions: wp_remote_post, wp_remote_get

 Alibaba Cloud

It is a common requirement to initiate HTTP requests. Generally, file_get_contents or cURL are used.

However, in WordPress, themes or plug-ins developed using file_get_contents or cURL will be officially rejected by WordPress. Because WordPress has officially provided encapsulated HTTP request functions. It was briefly introduced before that WordPress uses wp_remote_get and wp_remote_post to replace curl.

Want to be here? contact us bar
 Maker host

Wp_remote_get initiates GET request

Example:

  1.  $response  = wp_remote_get (  'https://Data URL'  ) ;
  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.  }

After the $body is obtained, it should be parsed according to the actual situation.

Wp_remote_post initiates POST request

  • 'headers' (string []) response header information.
  • 'body' (string) response body.
  • 'response '(array) corresponding data related to HTTP.
  • 'code' (int|false) HTTP CODE。
  • 'message '(string | false) HTTP corresponding message.
  • 'cookies' (WP_HTTP_Cookie []) cookies information.
  • 'http_response' (WP_HTTP_Requests_Response | null) The original HTTP response.

Example:

  1.  $response  = wp_remote_post (  $url ,  array (
  2.  'method'  =>  'POST' ,
  3.  'timeout'  =>  forty-five ,
  4.  'redirection'  =>  five ,
  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.   
  16.  if  ( is_wp_error (  $response  )  )  {
  17.  $error_message  =  $response -> get_error_message ( ) ;
  18.  echo  "Something went wrong: $error_message " ;
  19.  }  else  {
  20.  echo  'Response:<pre>' ;
  21.  print_r (  $response  ) ;
  22.  echo  '

';
}

Wp_remote_get sends GET request to URL and returns data Use the GET method to execute the HTTP request and return its response. Whether the parameter data type must describe the default value $url string [...]
Date: 2022/9/14 Reading: 512 read the whole passage

WordPress program remote data request functions: wp_remote_post, wp_remote_get

182 people have bought
View Demo Upgrade VIP Buy Now

Collection
fabulous ( zero )

Post reply

Hot selling template

Ashade - Works exhibition photo album WordPress Chinese theme
 LensNews

This site accepts WordPress/PbootCMS/DedeCMS, etc
System construction, imitation, development, customization and other services!