Post to WordPress with Google Scripts using XML-RPC API
You can use Google scripts to publish blog posts to any Blogger and WordPress website using the XML-RPC API. The script can be extended to create blog posts by email or you can even send a document from Google Docs and publish it your WordPress as a blog post.
The sample code demonstrates how to create a new post. You need to specify your WordPress site’s XML RPC endpoint, the user name and the password in “plain” text. The blog post may be published as a draft or public by changing the post_status parameter. If the blog post is published successfully, the post ID will be returned else it will return an error string.
To get started, do include the XML RPC library in your Google Apps Script project. The project key for the XML RPC library for Google Apps Script is My_8O8KRa_MszCVjoC01DTlqpU7Swg-M5 - choose the latest version from the dropdown and set the identifier as XMLRPC.
function postToWordPress() {
/* Add your WordPress credentials and replace example.com with your WordPress blog URL */
var wordpress = {
url: 'http://example.com/xmlrpc.php',
username: 'admin',
password: '12345',
};
/* Make sure your WordPress XML-RPC URL is correct */
var checkConfig = UrlFetchApp.fetch(wordpress.url, { muteHttpExceptions: true });
if (checkConfig.getResponseCode() !== 200) {
throw new Error('Please check your XML RPC URL');
}
/* Call the metaWeblog.newPost API method to create a new blog post */
var request = new XMLRPC.XmlRpcRequest(wordpress.url, 'metaWeblog.newPost');
/* The first parameter is empty since there's no blog ID for WordPress */
request.addParam('');
request.addParam(wordpress.username);
request.addParam(wordpress.password);
/* The blog post content. You can have HTML in the description */
var blogPost = {
post_type: 'post',
post_status: 'publish' /* Set to draft or publish */,
title: 'post title',
description: 'post description',
};
request.addParam(blogPost);
var response = request.send().parseXML();
Logger.log(response);
}
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory