Learning about wp_remote_post
In the beginning I was’t using wp_remote_get or wp_remote_post. In my Piwigo Embed plugin, I was doing some HTTP requests to get the gallery output to place inside a WordPress page. The intent was to be able to skin Piwigo independently from WordPress. I wanted the Piwigo content within the WordPress theme without having to recreate the look specifically for Piwigo. I was doing the requests using file_get_contents for GET requests and fopen for POST requests. It worked well for my purpose. I took the output and manipulated the URLs in links and for images and then spit the contents to a page using a shortcode.
This solution worked fine for me. I had control of the execution environment, so I didn’t have to worry about configuration not allowing fopen on URLs or anything like that. Then I saw and article about the WordPress wp_remote_get, wp_remote_post, and wp_remote_request functions. This seemed a much better solution to me. I prefer to use built-in tools if I can and these functions take care of the execution environment differences and would allow me to treat the get and post requests more similar to each other. I started modifying my code.
I ran into trouble very quickly. Piwigo needed a cookie set in order to access the admin functions. I tried setting the cookies as an associative array of cookie_name => cookie_value and sending that with my request. This failed. I then tried a simple array with name then value and this failed. I kept getting the error:
Fatal error: Call to a member function getHeaderValue() on a non-object. I looked around to find a solution to this problem but could not find one.
The documentation on this subject is poor in the WordPress Codex. It is mentioned that cookies are sent in the arguments associative array to the request, but the form of those cookies is not specified. It only mentions that the cookies need to be in an array. Then, I stumbled across this link and the answer was clear. The cookies needed to be set as objects of type WP_Http_Cookie. There is no mention of the WP_Http_Cookie object in the description of the wp_remote_get, wp_remote_post, or wp_remote_request functions. I also did not find it referenced in the articles I found online about these functions. It is because of the obscurity of this information that I write this post. I hope others will be spared the issues I ran into.
So the solution to the problem: If you need to send cookies with your wp_remote_get, wp_remote_post, wp_remote_request call, create the cookies at WP_Http_Cookie objects, add them to an array, and send them in the arguments labeled as ‘cookies’. Once I changed my code to use the WP_Http_Cookie object, it all worked fine. Hope this helps and happy coding!