Posting images and marking them featured to WordPress with XML-RPC and PHP

Posting images and marking them featured to WordPress with XML-RPC and PHP

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

For the sake of this exercise, I am assuming that you have a clear understanding of what XML-RPC is. If not, read more about it here. I am also assuming that XML-RPC is enabled on your wordpress blog and you have the required IXR_Library.php.inc downloaded from here.

The code below is self-explanatory.

Another assumption is that the image is already uploaded and posted to this page via a form.

<?php

$myFile = "myimage.jpg";
$fh = fopen($myFile, 'r');
$fs = filesize($myFile);
$theData = fread($fh, $fs);
fclose($fh);

$dom = 'Your Blog Path/xmlrpc.php';

$client = new IXR_Client($dom);
$username = "USERNAME";
$password = "PASSWORD"; 
 
$client->debug = true; //Set it to false in Production Environment
$params = array('name' => 'myimage.jpg', 'type' => 'image/jpg', 'bits' => new IXR_Base64($theData), 'overwrite' => true);
$res = $client->query('wp.uploadFile', 1, $username, $password, $params);
$clientResponse = $client->getResponse();
 
//echo URL &amp;amp; image id 
$thumbnail_image =  $clientResponse['url'];  
$thumbnail_id = $clientResponse['id'];
 
$title = "Blog Title"; // $title variable will insert your blog title
$body = "Blog Content"; // $body will insert your blog content (article content)
 
$category = "category1, category2"; // Comma seperated pre existing categories. Ensure that these categories exists in your blog.
$keywords = "keyword1, keyword2, keyword3";
 
$customfields = array('key'=>'Author-bio', 'value'=>'Autor Bio Here'); // Insert your custom values like this in Key, Value format
 
 
    $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),
        'custom_fields' =>  array($customfields),
        'wp_post_thumbnail' =>  $thumbnail_id, //thumbnail id of the picture, this will be marked as featured.
 
    );
    
$params = array(0, $username, $password, $content, true); // Last parameter is 'true' which means post immideately, to save as draft set it as 'false'
 
// Run a query for PHP
if (!$client->query('metaWeblog.newPost', $params)) 
{
    die('Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage());
}
else
{
    echo "Article Posted Successfully";
}

?>
No votes yet.
Please wait...
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Related Post