Uploading a picture in WordPress to your media gallery using xmlrpc

If you’re automatically creating a wordpress post or page from php code, rather than from the wordpress admin panel, sometimes you might need to add a pic from a different website to your upload directory, and then display that pic inside your wordpress page.
In This post, I will show you to how to upload a picture to your wordpress inside your media library and retrieve its URL using xmlrpc library.

The Code:

//make sure to include the correct path to class-IXR.php, depending on your  current Directoryr
include ‘wp-includes/class-IXR.php’; 

//Wordpress Username
$username = “myWpUsername”;
//Wordpress Password
$password = “myWpPassword”;
//make sure you specify the exact path to your xmlrpc.php
$xmlrpc_url = ‘http://mywebsite.com/xmlrpc.php’; 

$ixrClient = new IXR_Client($xmlrpc_url);

//url or image to add to the media library
$img = “http://wrmmedia.files.wordpress.com/2011/02/test-paper.jpg”;
//image_name.jpg
$image[‘name’] = md5($img). ‘.jpg’;
//type of image
$image[‘type’] = ‘image/jpg’;
//url or full path of an image
$image[‘bits’] = new IXR_Base64(file_get_contents($img));
//overwrite if exist
$image[‘overwrite’] = true;

//Upload the pic
if (!$ixrClient->query(‘wp.uploadFile’, ‘1’, $username, $password, $image))
{
    //If upload is unsuccessfull, write the error in error log
    error_log(‘An error occurred – ‘ . $ixrClient->getErrorCode() . “:” . $ixrClient->getErrorMessage());
}
else
{
     //Get Response
    $clientResponse = $ixrClient->getResponse();
    //echo URL of Image
    echo $clientResponse[‘url’];  
}

Any questions? Please leave a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *