WordPress

Making network requests with HTTP API

Syntax#

  • $response = wp_remote_get( $url, $args );
  • $response = wp_remote_post( $url, $args );
  • $response = wp_safe_remote_post( $url, $args );

Parameters#

Parameter Details
$url (string) (Required) Site URL to retrieve.
$args (array) (Optional) Request arguments.
## Remarks#
## Returns

(WP_Error | array) The response as an array, or WP_Error on failure.

GET a remote JSON resource

This snippet will grab a JSON formatted resource, decode it and print it in PHP array format.

// Fetch 
$response = wp_remote_get( 'https://www.example.com/resource.json' );

if ( ! is_wp_error( $response ) ) {
  $headers = wp_remote_retrieve_headers( $response );

  if ( isset( $headers[ 'content-type' ] ) && 'application/json' === $headers[ 'content-type' ] ) {
    print_r( json_decode( wp_remote_retrieve_body( $response ) ) );
  }
}

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow