Advertisement

XML-RPC in WordPress

by

XML-RPC is a protocol for remote procedure calls which uses XML for the data exchange and it mostly uses HTTP for the actual call. In XML-RPC the client that wants to make a call to a remote method creates the input parameters in the form of XML and sends it via an HTTP request to a remote server implementing the XML-RPC protocol. The remote server implementing the XML-RPC protocol gets the request and then performs the remote method and returns the result back in XML format.

In this article we are going to see how to call methods on your WordPress installation using XML-RPC.


Step 1 Understanding XML-RPC in WordPress

WordPress is a complete blogging platform. It is made highly customizable and open for other systems to connect and communicate with it. XML-RPC in WordPress helps this openness of WordPress by letting other systems or software perform operations on the WordPress installation, even remotely. So using WordPress XML-RPC can create WordPress blogging clients, some other software which does some batch tasks like creating multiple posts from a file, etc.


Step 2 Enabling XML-RPC Support on You WordPress Installation

By default XML-RPC is not enabled on your WordPress installation. So in order for your WordPress installation to be able to serve XML-RPC requests you have to enable this feature on you website.

To enable this feature you will have go to the admin section. There, under Settings -> Writing you will have to Enable the XML-RPC option as shown below.


Step 3 Knowing the Files and Classes in WordPress That Make XML-RPC Possible

All the XML-RPC requests are sent to the xmlrpc.php file which is present in your main WordPress installation directory. The file basically does a bootstrap for loading the WordPress environment and then creates an object of the class wp_xmlrpc_server which is present at the location wp-includes/class-wp-xmlrpc-server.php.

The wp_xmlrpc_server class is responsible for handling all the XML-RPC request coming from the XML-RPC clients.


Step 4 Knowing Different Types of APIs Supported by WordPress XML-RPC Server

WordPress XML-RPC server supports multiple types on APIs for XML-RPC. Following are the types of APIs that WordPress XML-RPC server supports:

  • WordPress API
  • Blogger API
  • MetaWeblog API
  • MovableType API
  • PingBack API

Though there is not much documentation on all this, a brief look at the wp_xmlrpc_server class will help to know the exact name of the APIs supported by WordPress' XML-RPC server.

function wp_xmlrpc_server() {
	$this->methods = array(
		// WordPress API
		'wp.getUsersBlogs'		=> 'this:wp_getUsersBlogs',
		'wp.getPage'			=> 'this:wp_getPage',
		'wp.getPages'			=> 'this:wp_getPages',
		'wp.newPage'			=> 'this:wp_newPage',
		'wp.deletePage'			=> 'this:wp_deletePage',
		'wp.editPage'			=> 'this:wp_editPage',
		'wp.getPageList'		=> 'this:wp_getPageList',
		'wp.getAuthors'			=> 'this:wp_getAuthors',
		'wp.getCategories'		=> 'this:mw_getCategories',		// Alias
		'wp.getTags'			=> 'this:wp_getTags',
		'wp.newCategory'		=> 'this:wp_newCategory',
		'wp.deleteCategory'		=> 'this:wp_deleteCategory',
		'wp.suggestCategories'	=> 'this:wp_suggestCategories',
		'wp.uploadFile'			=> 'this:mw_newMediaObject',	// Alias
		'wp.getCommentCount'	=> 'this:wp_getCommentCount',
		'wp.getPostStatusList'	=> 'this:wp_getPostStatusList',
		'wp.getPageStatusList'	=> 'this:wp_getPageStatusList',
		'wp.getPageTemplates'	=> 'this:wp_getPageTemplates',
		'wp.getOptions'			=> 'this:wp_getOptions',
		'wp.setOptions'			=> 'this:wp_setOptions',
		'wp.getComment'			=> 'this:wp_getComment',
		'wp.getComments'		=> 'this:wp_getComments',
		'wp.deleteComment'		=> 'this:wp_deleteComment',
		'wp.editComment'		=> 'this:wp_editComment',
		'wp.newComment'			=> 'this:wp_newComment',
		'wp.getCommentStatusList' => 'this:wp_getCommentStatusList',
		'wp.getMediaItem'		=> 'this:wp_getMediaItem',
		'wp.getMediaLibrary'	=> 'this:wp_getMediaLibrary',
		'wp.getPostFormats'     => 'this:wp_getPostFormats',

		// Blogger API
		'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs',
		'blogger.getUserInfo' => 'this:blogger_getUserInfo',
		'blogger.getPost' => 'this:blogger_getPost',
		'blogger.getRecentPosts' => 'this:blogger_getRecentPosts',
		'blogger.getTemplate' => 'this:blogger_getTemplate',
		'blogger.setTemplate' => 'this:blogger_setTemplate',
		'blogger.newPost' => 'this:blogger_newPost',
		'blogger.editPost' => 'this:blogger_editPost',
		'blogger.deletePost' => 'this:blogger_deletePost',

		// MetaWeblog API (with MT extensions to structs)
		'metaWeblog.newPost' => 'this:mw_newPost',
		'metaWeblog.editPost' => 'this:mw_editPost',
		'metaWeblog.getPost' => 'this:mw_getPost',
		'metaWeblog.getRecentPosts' => 'this:mw_getRecentPosts',
		'metaWeblog.getCategories' => 'this:mw_getCategories',
		'metaWeblog.newMediaObject' => 'this:mw_newMediaObject',

		// MetaWeblog API aliases for Blogger API
		// see http://www.xmlrpc.com/stories/storyReader$2460
		'metaWeblog.deletePost' => 'this:blogger_deletePost',
		'metaWeblog.getTemplate' => 'this:blogger_getTemplate',
		'metaWeblog.setTemplate' => 'this:blogger_setTemplate',
		'metaWeblog.getUsersBlogs' => 'this:blogger_getUsersBlogs',

		// MovableType API
		'mt.getCategoryList' => 'this:mt_getCategoryList',
		'mt.getRecentPostTitles' => 'this:mt_getRecentPostTitles',
		'mt.getPostCategories' => 'this:mt_getPostCategories',
		'mt.setPostCategories' => 'this:mt_setPostCategories',
		'mt.supportedMethods' => 'this:mt_supportedMethods',
		'mt.supportedTextFilters' => 'this:mt_supportedTextFilters',
		'mt.getTrackbackPings' => 'this:mt_getTrackbackPings',
		'mt.publishPost' => 'this:mt_publishPost',

		// PingBack
		'pingback.ping' => 'this:pingback_ping',
		'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks',

		'demo.sayHello' => 'this:sayHello',
		'demo.addTwoNumbers' => 'this:addTwoNumbers'
	);

Step 5 Creating the XMLRPClientWordPress Class in PHP

Now we are going to create a class XMLRPClientWordPress in PHP which will provide functions to perform different operations on your WordPress installation via XML-RPC calls.

class XMLRPClientWordPress
{
	var $XMLRPCURL = "";
	var $UserName  = "";
	var $PassWord = "";

First we will create a class and have three members in it to hold the value of the XML-RPC URL of the WordPress installation and the Username and Password of the installation.

The XML-PRC URL is http://yourwordpressinstall.com/xmlrpc.php, and the username and password are the username and password of a user of the blog with appropriate access.

Then we will create a constructor to take these values and store them in the class members as follows.

// Constructor
public function __construct($xmlrpcurl, $username, $password) 
{
	$this->XMLRPCURL = $xmlrpcurl;
	$this->UserName  = $username;
	$this->PassWord = $password;
}

Then we will create a send_request function which will take the request name and the parameters for the request as input. The function will then create an XML request from the input parameters and then send the request to the WordPress installation XML-RPC URL and return the results.

The function is as follows:

function send_request($requestname, $params)
{
	$request = xmlrpc_encode_request($requestname, $params);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
	curl_setopt($ch, CURLOPT_URL, $this->XMLRPCURL);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 1);
	$results = curl_exec($ch);
	curl_close($ch);
	return $results;
}

This function uses the PHP function xmlrpc_encode_request which creates the XML request then we use curl to send the request on the XML-RPC URL of the WordPress installation stored in the class member variable.

Then this function returns the result which it gets from the XML-RPC server.


Step 6 Sending the First SayHello XML-RPC Request to Your WordPress Installation

To check if we are able to call the methods on the WordPress installation server properly we will call demo.sayHello method, it takes no parameter and which if runs correctly the WordPress XML-RPC server returns a string "Hello!".

The function to call demo.sayHello is as follows:

function sayHello()
{
	$params = array();
	return $this->send_request('demo.sayHello',$params);
}

Basically as the demo.sayHello method does not take any parameters we send an empty array as the parameter and then call send_request by passing the request name as demo.sayHello.

To call this function you will need to create an object of class XMLRPClientWordPress as follows:

$objXMLRPClientWordPress = new XMLRPClientWordPress("http://localhost/wordpress31/xmlrpc.php" , "admin" , "abbas");

And then call:

$objXMLRPClientWordPress->sayHello()

The output of this will be as follows:

If you get the same result it means you are able to send the request properly to your WordPress XML-RPC server and receive the request properly.

Now you can perform a little more complex operation using XML-RPC on your WordPress installation.


Step 7 Creating a Post Your Blog Using XML-RPC

Now let's create a function which will create a post on the blog through XML-RPC.

The request name for creating a post is metaWeblog.newPost which is actually a part of the MetaWeblog API that WordPress supports.

The arguments required for this request are the

  • blogid ( which is 0 if you have only one blog on your installation)
  • username
  • password
  • Content Structure of the post i.e. different information about the post like title, content, categories etc.
  • publish i.e. whether to publish the post

The function create_post is as follows:

function create_post($title,$body,$category,$keywords='',$encoding='UTF-8')
{
	$title = htmlentities($title,ENT_NOQUOTES,$encoding);
	$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

	$content = array(
		'title' => $title,
		'description' => $body,
		'mt_allow_comments' => 0,  // 1 to allow comments
		'mt_allow_pings' => 0,  // 1 to allow trackbacks
		'post_type' => 'post',
		'mt_keywords' => $keywords,
		'categories' => array($category)
	);
	$params = array(0,$this->UserName,$this->PassWord,$content,true);

	return $this->send_request('metaWeblog.newPost',$params);
}

This function takes the title, body , categories etc as input arguments . Then it creates a content structure from these arguments and sets some default values.

Then we will create a parameter array from the username, password previously passed in the constructor and from the content array we made from the input parameters.

This function can be called as follows.

$objXMLRPClientWordPress->create_post('Hello WordPress XML-RPC', 'This is the content of post done via XML-RPC','');

The post ID of the newly created post is the value returned by this API. If we create a table from the API and print its results it will look as follows.

If we go and see the WordPress installation the post will appear on it as follows


Step 8 Creating a Page Your Blog Using XML-RPC

Now we will create a page on the WordPress installation using the XML-RPC. The request for creating a page is wp.newPage which is actually a part of the WordPress API.

The arguments for this are same as that for the creation of post request.

Following is the create_page function:

function create_page($title,$body,$encoding='UTF-8')
{
	$title = htmlentities($title,ENT_NOQUOTES,$encoding);

	$content = array(
		'title' => $title,
		'description' => $body
	);
	$params = array(0,$this->UserName,$this->PassWord,$content,true);

	return $this->send_request('wp.newPage',$params);
}

This basically takes the title and body as inputs and then creates the parameters required for the request, then sends the request.

We will call the function as follows

$objXMLRPClientWordPress->create_page('WordPress XML-RPC page', 'This is the content of First Page done via XML-RPC');

And then call:

$objXMLRPClientWordPress->sayHello()

The return for this request is the page id of the newly created page. Now if we run this function and check our WordPress installation, the newly created page will be seen as follows.


Step 9 Getting the List of Authors of a Blog Using XML-RPC

Now we will create a function to get the author list from your WordPress installation via XML-RPC. The request for getting the list of authors is wp.getAuthors which is also a part of the WordPress API.

The parameters for this request are as follows:

  • blogid ( which is 0 if you have only one blog on your installation )
  • username
  • password

The function display_authors is as follows:

function display_authors()
{
	$params = array(0,$this->UserName,$this->PassWord);
	return $this->send_request('wp.getAuthors',$params);
}

It does not take any parameters just uses the stored username and password to send the request. The output of this function is a string about the author details of all the authors on the blog.

We can call this function as follows:

$objXMLRPClientWordPress->display_authors();

Following is the table created from the request and response of the different requests in this tutorial.


Step 10 Knowing About Some Other Important Operation Supported by WordPress XML-RPC

Like the other requests discussed, WordPress supports almost all the important operations one can perform on WordPress.

There are requests supported for

  • Creating, editing, deleting pages and posts
  • Creating, editing, deleting comments
  • Listing authors and blog details
  • For getting recent posts and list of categories

And lots more are supported.


Conclusion

XML-RPC support on WordPress enables one to write other software or scripts which can automate tasks on your WordPress installation or some other client software to perform tasks remotely.

Features such as XML-RPC help WordPress to be a very open and extensible platform. So happy blogging with WordPress!

Do you have a particular task you like to use XML-RPC for? Is there specific software you like to use with WordPress that utilises XML-RPC? Let us know in the comments below!

Advertisement