wp_remote_post

Home » Functions » wp_remote_post

WordPress provides a number of functions that make it easy to interact with remote servers and APIs. One of these functions is wp_remote_post, which allows you to send a POST request to a specified URL.

This function is particularly useful when building WordPress plugins or themes that need to interact with external APIs or web services. For example, you might use wp_remote_post to send data to a remote server for processing, or to retrieve data from an API.

To use wp_remote_post, you’ll need to specify the URL you want to send the POST request to, as well as any additional parameters or data that need to be sent along with the request. You can also specify a number of optional parameters, such as the timeout value, the user agent string, and whether or not to use SSL.

Here’s an example of how to use wp_remote_post to send a POST request with some sample data:

$url = 'https://example.com/api/endpoint';
$data = array(
   'name' => 'John Smith',
   'email' => 'john@example.com',
   'message' => 'Hello, World!'
);

$response = wp_remote_post( $url, array(
   'method' => 'POST',
   'timeout' => 45,
   'redirection' => 5,
   'httpversion' => '1.0',
   'blocking' => true,
   'headers' => array(),
   'body' => $data,
   '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>';
}

In this example, we’re sending a POST request to the URL ‘https://example.com/api/endpoint‘, with the data array containing the name, email, and message fields. We’re also setting a timeout value of 45 seconds, and specifying that we want the response to be blocking (meaning the script will wait for the response).

If an error occurs, we’re printing out an error message. Otherwise, we’re printing out the entire response object for debugging purposes.

Overall, wp_remote_post is a powerful WordPress function that makes it easy to interact with remote servers and APIs.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.