A primer on how to use the HTTP API in WordPress for remote communication. Learn best practices, review different web service approaches, and watch a practical example copy a post from one WordPress install to another using XML-RPC.
Use the Wrappers wp-includes/http.php wp_remote_request() Retrieve the raw response from the HTTP request. wp_remote_get() Retrieve the raw response from the HTTP request using the GET method. wp_remote_post() Retrieve the raw response from the HTTP request using the POST method. wp_remote_head() Retrieve the raw response from the HTTP request using the HEAD method. Friday, November 2, 12
Helpful Functions wp-includes/http.php wp_remote_retrieve_headers() Retrieve only the headers from the raw response. wp_remote_retrieve_response_code() Retrieve the HTTP stats response code from the raw response. wp_remote_retrieve_response_messsage() Retrieve the HTTP status response message from the raw response. wp_remote_retrieve_body() Retrieve only the body from the raw response. Friday, November 2, 12
Get the post from WordPress $post = get_post($post_id); Pass the $post_id from our function argument Get the post stdClass back in $post Friday, November 2, 12
Make sure the post exists if ( is_null($post) ) { error_log( sprintf($errorlog,__("$post_id was not found.")) ); return false; } Log an error, and bail with a boolean result of false Friday, November 2, 12
Copy the post data $content = array( 'post_type' => $post->post_type, 'post_title' => "{$post->post_title} Copy", 'post_content' => $post->post_content, 'post_status' => 'draft', 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, ); Duplicate the data for the $content argument of the request Friday, November 2, 12
Format the request $request = xmlrpc_encode_request( 'wp.newPost', array( $blogid, $user, $pwd, $content ) ); Pack the request using xmlrpc_encode_request method, blog id, user name, password, the post content Friday, November 2, 12
Hailing frequencies open... $result = wp_remote_post( $url, array('body' => $request) ); Send the xml encoded request in the body parameter Get the result back Friday, November 2, 12
Parse the response $body = wp_remote_retrieve_body($result); $XML = simplexml_load_string($body); Grab the body from the result Parse the XML data into a structured object Friday, November 2, 12
References HTTP API http://codex.wordpress.org/HTTP_API How to Make HTTP Requests with WordPress http://planetozh.com/blog/2009/08/how-to-make-http-requests-with-wordpress/ A Note on WP_Http and HTTP Requests in WordPress http://kovshenin.com/2011/a-note-on-wp_http-and-http-requests-in-wordpress/ WP_Http class wp-includes/class-http.php WP_Http functions wp-includes/http.php Friday, November 2, 12