Publishing posts to Wordpress with API on XML RPC

en-US | создано: 23.12.2017 | опубликовано: 23.12.2017 | обновлено: 02.01.2018 | просмотров за всё время: 2008

In this article talk about publishing posts to WordPress blog using XML RPC (API). Also it explain how to use Calabonga.XmlRpcClient nuget-package to do posting.

XML RPC

In wiki there is an information:

XML-RPC is a remote procedure call (RPC) protocol which uses XML to encode its calls and HTTP as a transport mechanism.[1] "XML-RPC" also refers generically to the use of XML for remote procedure call, independently of the specific protocol. This article is about the protocol named "XML-RPC".

The XML-RPC protocol was created in 1998 by Dave Winer of UserLand Software and Microsoft,[2] with Microsoft seeing the protocol as an essential part of scaling up its efforts in business-to-business e-commerce.[3] As new functionality was introduced, the standard evolved into what is now SOAP.[4]

UserLand supported XML-RPC from version 5.1 of its Frontier web content management system,[4] released in June 1998.[5]

XML-RPC's idea of a human-readable-and-writable, script-parsable standard for HTTP-based requests and responses has also been implemented in competing specifications such as Allaire's Web Distributed Data Exchange (WDDX) and webMethod's Web Interface Definition Language (WIDL).[6] Prior art wrapping COMCORBA, and Java RMI objects in XML syntax and transporting them via HTTP also existed in DataChannel's WebBroker technology.[7][8]

The generic use of XML for remote procedure call (RPC) was patented by Phillip Merrick, Stewart Allen, and Joseph Lapp in April 2006, claiming benefit to a provisional application filed in March 1998. The patent is assigned to webMethods, located in Fairfax, VA.[9]

I managed to write an XML RPC Client NuGet package that can send requests and process responses over XML RPC without binding to a particular service.

Wordpress

I have a blog on the WordPress site. Rarely, but it happens that I publish there posts that are not related to programming. I want to show how to post message to the Wordpress site using API (XML RPC). For this I want to demonstrate how my library Calabonga.XmlRpcClient works. Lets go!

For demo purpose I've been created a console application. Then I install library from nuget:

The service provides extensive capabilities for managing entities through the API. Here are the main methods:

I created a small class in which I have written only some of the following methods:

public class WordpressClient {
    public const string ApiUrl = "https://calabonga.wordpress.com/xmlrpc.php";
    public const string Login = "WordPressAccount";
    public const string Password = "xxxxxxxxxxxxxxx";
    public const int UserId = 000000;
    public const int BlogId = 0;
 
    public class Requests {
        public const string Hello = "demo.sayHello";
        public const string GetUser = "wp.getUser";
        public const string GetUsers = "wp.getUsers";
        public const string GetProfile = "wp.getProfile";
        public const string GetAuthors = "wp.getAuthors";
        public const string GetPosts = "wp.getPosts";
        public const string GetPost = "wp.getPost";
        public const string GetNewPost = "wp.newPost";
        public const string GetPostType = "wp.getPostType";
        public const string GetPostStatusList = "wp.getPostStatusList";
        public const string GetPostTypes = "wp.getPostTypes";
        public const string GetMediaLibrary = "wp.getMediaLibrary";
        public const string GetMediaItem = "wp.getMediaItem";
        public const string UploadFile = "wp.uploadFile";
    }
}

In line 2 you can see the base URL for my blog. You have to find your URL in documentation. Futher, in main mecthod i've created an some functions call:

class Program {
 
    private static readonly XmlRpcClient Client = 
                 new XmlRpcClient { Url = WordpressClient.ApiUrl };
 
    static void Main(string[] args) {
 
        GetHelloMessage();
 
        GetPostStatusList();
 
        GetPostTypeList();
 
        GetPosts();
 
        GetPost(666);
 
        GetMediaLibrary();
 
        GetMediaItem(185);
    }
 
    // some code was removed for brevity
}

Further we will analyze each of the created methods.

demo.sayHello

This method can help you to test the service is working correctly.

private static void GetHelloMessage() {
    var request = new XmlRpcRequest(WordpressClient.Methods.Hello);
    var result = Client.Execute(request);
    if (result.XmlRpcResponse.IsFault()) {
        Console.WriteLine(result.XmlRpcResponse.GetFaultString());
    }
    Console.WriteLine(result.XmlRpcResponse.GetString());
}

The result of this method call is:

wp.getPostStatusList

This method returns the list of the posts.

private static void GetPostStatusList() {
    var request = new XmlRpcRequest(WordpressClient.Methods.GetPostStatusList);
    request.AddParams(WordpressClient.BlogId, WordpressClient.Login, WordpressClient.Password);
    var result = Client.Execute(request);
    if (result.XmlRpcResponse.IsFault()) {
        Console.WriteLine(result.XmlRpcResponse.GetFaultString());
    }
    Console.WriteLine(result.XmlRpcResponse.GetString());
}

The result is:

Sorry, a this moment I have no post in Engrlish, just trust me that is works fine. :)

wp.getPostTypes

This method returns a list of available types for post:

private static void GetPostTypeList() {
    var request = new XmlRpcRequest(WordpressClient.Methods.GetPostTypes);
    request.AddParams(WordpressClient.BlogId, WordpressClient.Login, WordpressClient.Password);
    var result = Client.Execute(request);
    if (result.XmlRpcResponse.IsFault()) {
        Console.WriteLine(result.XmlRpcResponse.GetFaultString());
    }
    Console.WriteLine(result.XmlRpcResponse.GetString());
}

The result is a lot of JSON data. I have slightly reduced it:

wp.getPosts

This can returns your posts as paged list.

private static void GetPosts() {
    var request = new XmlRpcRequest(WordpressClient.Methods.GetPosts);
    request.AddParams(WordpressClient.BlogId, WordpressClient.Login, WordpressClient.Password);
    var result = Client.Execute(request);
    if (result.XmlRpcResponse.IsFault()) {
        Console.WriteLine(result.XmlRpcResponse.GetFaultString());
    }
    var posts = result.XmlRpcResponse.GetObject();
    Console.WriteLine(JsonConvert.SerializeObject(posts));
}

The result is:

wp.getPost

This method returns a post by ID. In the previous call I have a list of posts, then I can request info about any post by ID:

private static void GetPost(int postId) {
    var request = new XmlRpcRequest(WordpressClient.Methods.GetPost);
    request.AddParams(WordpressClient.BlogId, WordpressClient.Login, WordpressClient.Password, postId);
    var result = Client.Execute(request);
    if (result.XmlRpcResponse.IsFault()) {
        Console.WriteLine(result.XmlRpcResponse.GetFaultString());
    }
    var post = result.XmlRpcResponse.GetObject();
    Console.WriteLine(JsonConvert.SerializeObject(post));
}

And again the result is:

wp.getMediaLibrary

This method returns a collection of media files. In my case it is a collectioon of the images from my blog posts.

private static void GetMediaItem(int attachmentId) {
    var request = new XmlRpcRequest(WordpressClient.Methods.GetMediaItem);
    request.AddParams(WordpressClient.BlogId, WordpressClient.Login, WordpressClient.Password, attachmentId);
    var result = Client.Execute(request);
    if (result.XmlRpcResponse.IsFault()) {
        Console.WriteLine(result.XmlRpcResponse.GetFaultString());
    }
    var library = result.XmlRpcResponse.GetString();
    Console.WriteLine(library);
}

And the result of call is:

You can check it out. Everything works extremely fast and very correctly.

Conclution

I've shown some examples of how to use a nuget XML RPC Client package. In turn, you can easily implement other methods you need by looking at the method parameters in the documentation. In the examples, I did not deserialize to the objects coming from the server, but you can do this, for example, by using the Newtonsoft. JSON Library. I think it is clear that to add a new article to the blog on Wordpress should be implemented in this way the method of wp. newPost.

In other words, the CalabongaXmlRpcClient turned out to be universal, you can use it to work with any XML RPC services.

Комментарии к статье (2)

08.08.2018 19:21:25 Kay

Hi,

would it be possible to show an example to create a new blog post? I am trying for a while not, but I always get an error 500 with "Error sending request".

XmlRpcClient Client = new XmlRpcClient { Url = WordpressClient.ApiUrl };

Post myPost = new Post
{
   PostType = "page",
   Body = "Das ist der Body",
   Title = "Das ist der Title",
   Categories = new string[] { "Allgemein" },
   DateCreated = DateTime.Now,   
   CustomFields = new CustomField[] { },
   Tags = new string[] { },
   Terms = new Term[] { }
};

try
{
	var request = new XmlRpcRequest(WordpressClient.Requests.GetNewPost);
	request.AddParams(0, WordpressClient.Login, WordpressClient.Password, myPost.ToString());
	var result = client.Execute(request);
	if (result.XmlRpcResponse.IsFault())
	{
		Console.WriteLine(result.XmlRpcResponse.GetFaultString());
	}
	Console.WriteLine(result.XmlRpcResponse.GetString());
}
catch (Exception ex)
{

}      
      
Where Post is defined as

public class Post
    {
        public Post() { }

        public int PostID { get; set; }
        public DateTime DateCreated { get; set; }
        public string Body { get; set; }
        public string Title { get; set; }
        public string Permalink { get; set; }
        public string[] Categories { get; set; }
        public string[] Tags { get; set; }
        public CustomField[] CustomFields { get; set; }
        public Term[] Terms { get; set; }
        public string PostType { get; set; }        
    }

    public class CustomField
    {
        public CustomField() { }
        public string ID { get; set; }
        public string Key { get; set; }
        public string Value { get; set; }
    }

    public class Term
    {
        public Term() { }

        public string Taxonomy { get; set; }
        public string[] Terms { get; set; }
    }

Best regards!

 

08.08.2018 19:30:15 Calabonga

Did you try a simple requests? Something get from your blog? Does the publishing from remote clients is allowed?

I guess two-way authentication enabled, am I right?

I think you should ask wordpress support about this issue. 

Как в вам обращаться?
используется для обратной связи (не публикуется)
пример: https://www.calabonga.com
  1. Отправляя комментарий и предоставляя сайту персональные данные, вы соглашаетесь с Политикой конфиденциальности, которая установлена на сайте.
  2. Все комментарии модерируются на предмет наличия идиоматических выражений и нецензурных слов. Теги-ссылки будут удалены из текста сообщения.