How to Publish a WordPress Post Remotely Using PHP

WordPress provides XML-RPC that can be used to retrieve and maniputate WordPress posts.

If you want to publish a post to any wordpress website remotely then it can be done using the following code.

<?php

// This will publish the posts.
function publish_post_xmlrpc($request,$BLOGURL) {
        //Initializing CURL 
        $ch = curl_init();

        //The URL to be downloaded is set 
        curl_setopt($ch, CURLOPT_URL, $BLOGURL."/xmlrpc.php");
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // this will return the post id

        //Now execute the CURL, download the URL specified 
        $response = curl_exec($ch);
        $response = xmlrpc_decode($response);
        curl_close($ch);
        if(isset($response)) {
            return $response;
        }           

}


// PROCESS START FROM HERE.
// Site url only.NOT the sitelogin url
$BLOGURL =   '<your site>'; 

$USERNAME =  'username';

$PASSWORD =  'password';


// post details
$title = 'This is remote post title';
$description  = 'Remote post contents is goes here';


//Forming the content of blog post 
$content['title'] = $title;
$content['description'] = $description;

$content['categories'] = array(1); 
// category id.You can send category ids as array

$content['post_status'] = 'draft'; // publish | pending | draft

// process begin
$toPublish = true;//Whether the post has to be published 

$request = xmlrpc_encode_request("metaWeblog.newPost",array(0,$USERNAME, $PASSWORD, $content, true));

// call to the remote function
$postID = publish_post_xmlrpc($request,$BLOGURL); // return the post id
echo $postID;

?>

The publish_post_xmlrpc takes the $request object and $BLOGURL as parameters and publishes the post to wordpress.

This content has been helpful to you?

Thanks for contributing!

Yes No