WP JSON RPC API

Wow, that’s a lot of acronyms! Here’s my current version of the plugin:

Download

To see what it’s about, please see this WordPress trac ticket..

I’ll add it to the WP plugins repository as soon as I make sure it works with 3.1 and has a sample use case I can release.

A typical call:

// in JS (check that wpJSON is defined somewhere prior)
wpJSON.request(
   'myplugindomain.someRPCMethodNameHere', 
   {parameterName:'parameter value'}, 
   function ( result ) { 
          // handle the successful result object here
   },
   function( code, error, data ) { 
      // handle the error object here
   }
);

On the server side of your plugin, you can do something like this:

class My_Plugin_Control_Class {
   public function __construct()
   {
          add_filter('json_server_classname', array(&$this, 'filter_json_server_classname'), 10, 2);
   }

   public function filter_json_server_classname( $server_class = '', $method = '' )
   {
      switch( $method ) :
         case 'myplugindomain.someRPCMethodNameHere' : 
         case 'myplugindomain.someOtherRPCMethodNameHere' :
            $server_class = 'My_Plugin_JSON_RPC_Server';
         break;
      endswitch;
      return $server_class;
   }
}

// instantiate your control class somewhere

// extend the JSON class

class My_Plugin_JSON_RPC_Server extends WP_JSON_RPC_Server {
    
   public function __construct()
   {
      $this->methods['myplugindomain.someRPCMethodNameHere'] = 'this:someRPCMethodNameHere';
      $this->methods['myplugindomain.someOtherRPCMethodNameHere'] = 'this:someOtherRPCMethodNameHere';
   }

   public function someRPCMethodNameHere( $args )
   {
      if ( isset( $args->{'parameterName'} ) ) {
         // let's do something with this data!

         return array(
            'response-param-name' => __('We did something!', 'my-fancy-plugin'),
         );
      } else {
         return new WP_Error(
            -32602,
            __('Invalid method parameters:  myplugindomain.someRPCMethodNameHere must receive a value in the parameterName parameter.', 'my-fancy-plugin')

         );
      }
   }

   ...
}

Post a Comment

Your email is never shared. Required fields are marked *

*
*