A WordPress Plugin – Hello XML-RPC World

|

In a previous post (How Can I Modify The WordPress XML-RPC System?) I outlined how one might create a plugin that adds functionality to the WordPress XML-RPC server. I’ve had some questions from some readers arise so I wanted to take the opportunity to provide a more concrete and usable example.

WordPress Plugin

First you are going to create your plugin. This can be a single file that follows all of the regular WordPress plugin flow. I have a complete plugin example listed below.

function wpHelloXMLRPCWorld($args) {
  return "Hello XML-RPC World!";
}

function attach_new_xmlrpc($methods) {
    $methods['wpHelloXMLRPC.helloWorld'] = 'wpHelloXMLRPCWorld';
    return $methods;
}
add_action('xmlrpc_methods', 'attach_new_xmlrpc');

Of course, for simplicity sake in this post I’ve eliminated comment blocks. You’ll need those in order for your plugin to be properly recognized by WordPress. Other than that this is it. The wpHelloXMLRPCWorld method is the actual method that does the work of whatever you want. This one simply returns a hello world string. The attach_new_xmlrpc method is used to do the work of registering your new XML-RPC method. And finally we just need to add the action to tell WordPress to use our attach_new_xmlrpc method to attach our new XML-RPC function.

Testing With Java

I personally like the Redstone XML-RPC library, which I’ve written on before (Would You Like To Post To WordPress From Java?). This is a very simple Java class which can test the new XML-RPC function.

import redstone.xmlrpc.XmlRpcClient;

public class TestWPHelloXmlRpc
{
  public static void main( String[] args )
  {
    if( args.length == 0 )
    {
      System.out.println("\nUsage: java TestWPHelloXmlRpc \n");
    }
    else
    {
      try
      {
        XmlRpcClient client = new XmlRpcClient(args[0], false);
        String rMethod = "wpHelloXMLRPC.helloWorld";
        // String rMethod = "demo.sayHello";
        Object retVal = client.invoke(rMethod, new Object[]{});
        System.out.println("XML-RPC Response : " + (String)retVal);
      }
      catch(Exception e)
      {
        e.printStackTrace(System.err);
      }
    }
  }
}

Download

This is a complete example that includes:

  1. The PHP file needed for the plugin. Just upload wpHelloXMLRPC.php to your wp-content/plugins directory and activate as usual for WordPress plugins.
  2. The Java program which can run your new XML-RPC method.
  3. A bat file (dos/Windows) that will compile the Java test program.
  4. A jar file containing the required Redstone libraries

wpHelloXMLRPC.zip