Skip to content
Advertisement

WordPress cURL and wp_remote_post

So my problem is that i used until now in one of my wordpress plugins cURL for a POST request, but now i need to use wp_remote_post().

wp_remote_post seems simple but i can’t get it to work. So my question is: could someone show my how the following cURL can be transfered to wp_remote_post ?

The cURL:

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));
$result = curl_exec($ch);
curl_close($ch);

My version of wp_remote_post

$result = wp_remote_post($url, array(
    'method' => 'POST',
    'headers' => $headers,
    'body' => json_encode($fields) )
);

I get a 401 error with wp_remote_post because the authorization didn’t work.

Advertisement

Answer

I solved it. For some reason it is working now, after adding httpversion and the sslverify. Hope this helps someone:

$result = wp_remote_post($url, array(
        'method' => 'POST',
        'headers' => $headers,
        'httpversion' => '1.0',
        'sslverify' => false,
        'body' => json_encode($fields))
    );
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement