Site icon Freelance Web Developer, Web Designer Mumbai India

XML-RPC in WordPress

In this article I will explain XML RPC support in WordPress. Let’s discuss XML RPC first. It is Remote Procedure Calling using HTTP transport and XML encoding. It allows to send data structure that can be processed in the remote server and returns.

WordPress has inbuilt implementation for XML RCP interface. Let’s discuss about how to add custom method and execute from remote server using HTTP as transport.

WordPress has “xmlrpc_call” action and “xmlrpc_methods” method.

“xmlrpc_call” action is called after the XML RPC user is authenticated but before performing the method logic.

“xmlrpc_methods” filter can be used to add custom method to WordPress XML RPC.

Please check below code to register custom method.


function custom_method_name ( $args ) {
//$args[0], $args[1] will be available as arguments.
// Write your method logic here and return
return $returnvalue;
}

function add_custom_xmlrpc_methods ( $methods ) {
$methods['mynamespace.subtractTwoNumbers'] = 'custom_method_name';
return $methods;
}
add_filter( 'xmlrpc_methods', 'add_custom_xmlrpc_methods');

To call this method from remote server please check below code.


function sendXMLRPC($remoteurl, $requestname, $params = []) {
$request = xmlrpc_encode_request($requestname, $params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $remoteurl);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 500);
$results = curl_exec($ch);
curl_close($ch);
if ($results === false) {
return curl_error($ch);
} else {
return xmlrpc_decode($results);
}
}
Hope this helps.
Exit mobile version