Post on your WordPress blog using PHP

July 1, 2009 at 9:17 am

Who said you have to be logged on your WordPress dashboard to publish a new post on your blog? PHP and cURL can do it easily for you. Let see how.

Here is the function. This code is not made for being used within WordPress, so don’t paste it on your functions.php file (or any other).

Please note that you must activate the XMLRPC posting option in your WordPress blog. If this option isn’t activated, the code will not be able to insert anything into your blog database. Another thing, make sure the XMLRPC functions are activated on your php.ini file.

function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') {
    $title = htmlentities($title,ENT_NOQUOTES,$encoding);
    $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

    $content = array(
        'mt_allow_comments'=>0,  // 1 to allow comments
        'mt_allow_pings'=>0,  // 1 to allow trackbacks
    $params = array(0,$username,$password,$content,true);
    $request = xmlrpc_encode_request('metaWeblog.newPost',$params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_URL, $rpcurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $results = curl_exec($ch);
    return $results;

If you’re interested in that kind of stuff (PHP/cURL) you should definitely have a look at the 10 awesome things to do with cURL list I published two days ago on my other blog Cats Who Code.

Credits :