How to create a new post with a photo attached to WordPress using XMLRPC?

Does anyone know how to create a new post with a photo attached to WordPress using XMLRPC?

I can create a new message and upload a new picture separately, but it seems that there is no way to attach the downloaded photo to the created record?

Below are the codes that I am currently using.

<?php
DEFINE('WP_XMLRPC_URL', 'http://www.blog.com/xmlrpc.php');
DEFINE('WP_USERNAME', 'username');
DEFINE('WP_PASSWORD', 'password');

require_once("./IXR_Library.php");
$rpc = new IXR_Client(WP_XMLRPC_URL);
$status = $rpc->query("system.listMethods"); // method name
if(!$status){
    print "Error (".$rpc->getErrorCode().") : ";
    print $rpc->getErrorMessage()."\n";
    exit;
}

$content['post_type'] = 'post'; // post title
$content['title'] = 'Post Title '.date("F j, Y, g:i a"); // post title
$content['categories'] = array($response[1]['categoryName']); // psot categories
$content['description'] = '<p>Hello World!</p>'; // post body
$content['mt_keywords'] = 'tag keyword 1, tag keyword 2, tag keyword 3'; // post tags
$content['mt_allow_comments'] = 1; // allow comments
$content['mt_allow_pings'] = 1; // allow pings
$content['custom_fields'] = array(array('key'=>'Key Name', 'value'=>'Value One')); // custom fields
$publishBool = true;

if(!$rpc->query('metaWeblog.newPost', '', WP_USERNAME, WP_PASSWORD, $content, $publishBool)){
    die('An error occurred - '.$rpc->getErrorCode().":".$rpc->getErrorMessage());
}
$postID = $rpc->getResponse();
echo 'POST ID: '.$postID.'<br/>';

if($postID){ // if post has successfully created

    $fs = filesize(dirname(__FILE__).'/image.jpg');
    $file = fopen(dirname(__FILE__).'/image.jpg', 'rb');
    $filedata = fread($file, $fs);
    fclose($file);

    $data = array(
        'name'  => 'image.jpg',
        'type'  => 'image/jpg',
        'bits'  => new IXR_Base64($filedata),
        false // overwrite
    );

    $status = $rpc->query(
        'metaWeblog.newMediaObject',
        $postID,
        WP_USERNAME,
        WP_PASSWORD,
        $data
    );
    echo print_r($rpc->getResponse()); // Array ( [file] => image.jpg [url] => http://www.blog.com/wp-content/uploads/2011/09/image.jpg [type] => image/jpg )
}
?>
+5
source share
6 answers

I participated in WordPress sites (my current employer used 3 of them) and posted stuff daily, but actually forced me to use what I do best - scripts!

PHP . ? .htaccess, .

, XMLRPC, , - , Wordpress . , ! , .

. , . 100% , XMLRPC, !

WordPress:

  • class-IXR.php, /wp -admin/includes
  • class-wp-xmlrpc-server.php, /wp -include

class-IXR.php , , . base64. , PHP.

, . .

  • -wp-xmlrpc-server.php

    • ftp. .
    • . , ( , , , unix-, ), - ultraedit.
    • mw_newMediaObject. . ; WordPress blogger movabletype. WordPress xmlrpc, , , .
    • mw_newMediaObject($args). , 2948. , , . , , / .
    • , - :

       $name = sanitize_file_name( $data['name'] );
       $type = $data['type'];
       $bits = $data['bits'];
      
    • $name -. . .

       $name = sanitize_file_name( $data['name'] );
       $post = $data['post']; //the post ID to attach to.
       $type = $data['type'];
       $bits = $data['bits'];
      

      $post. , , "post".

      , , xmlrpc. , . .

      , , 3000.

      // Construct the attachment array
      // attach to post_id 0
      $post_id = 0;
      $attachment = array(
          'post_title' => $name,
          'post_content' => '',
          'post_type' => 'attachment',
          'post_parent' => $post_id,
          'post_mime_type' => $type,
          'guid' => $upload[ 'url' ]
      );
      
    • , - ! 0 post_parent! .

      // Construct the attachment array
      // attach to post_id 0
      $post_id = $post;
      $attachment = array(
          'post_title' => $name,
          'post_content' => '',
          'post_type' => 'attachment',
          'post_parent' => $post_id,
          'post_mime_type' => $type,
          'guid' => $upload[ 'url' ]
      );
      

      $post_id $post, xmlrpc. , , !

      . , , . , XMLRPC, .

    • , . , .

      WordPress, . , !

  • -IXR.php PHP-. - , .: (

, .

+9

, WordPress IMG. WP , -. , .

:

  • ()
  • URL-
  • URL- IMG .

. .

$admin ="***";
$userid ="****";
$xmlrpc = 'http://localhost/web/blog/xmlrpc.php';
include '../blog/wp-includes/class-IXR.php';
$client = new IXR_Client($xmlrpc);

$author         =   "test";    
$title          =   "Test Posting";
$categories     =   "chess,coolbeans";
$body           =   "This is only a test disregard </br>";

$tempImagesfolder = "tempImages";
$img = "1338494719chessBoard.jpg";


$attachImage = uploadImage($tempImagesfolder,$img);
$body .= "<img src='$attachImage' width='256' height='256' /></a>";

createPost($title,$body,$categories,$author);

/*
*/
function createPost($title,$body,$categories,$author){
    global $username, $password,$client;
    $authorID =  findAuthor($author); //lookup id of author

    /*$categories is a list seperated by ,*/
    $cats = preg_split('/,/', $categories, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($cats as $key => $data){
        createCategory($data,"","");
    }

    //$time = time();
    //$time += 86400;
    $data = array(
        'title' => $title,
        'description' => $body,
        'dateCreated' => (new IXR_Date(time())),
        //'dateCreated' => (new IXR_Date($time)),  //publish in the future
        'mt_allow_comments' => 0, // 1 to allow comments
        'mt_allow_pings' => 0,// 1 to allow trackbacks
        'categories' => $cats,
        'wp_author_id' => $authorID     //id of the author if set       
    );
    $published = 0; // 0 - draft, 1 - published
    $res = $client->query('metaWeblog.newPost', '', $username, $password, $data, $published);
}

/*
*/
function uploadImage($tempImagesfolder,$img){
    global $username, $password,$client;
    $filename = $tempImagesfolder ."/" . $img;

    $fs = filesize($filename);   
    $file = fopen($filename, 'rb');  
    $filedata = fread($file, $fs);    
    fclose($file); 

    $data = array(
        'name'  => $img, 
        'type'  => 'image/jpg',  
        'bits'  => new IXR_Base64($filedata), 
        false //overwrite
    );

    $res = $client->query('wp.uploadFile',1,$username, $password,$data);
    $returnInfo = $client->getResponse();

    return $returnInfo['url'];     //return the url of the posted Image
}

/*
*/
function findAuthor($author){
    global $username, $password,$client;
    $client->query('wp.getAuthors ', 0, $username, $password);
    $authors = $client->getResponse();
    foreach ($authors as $key => $data){
        //  echo $authors[$key]['user_login'] . $authors[$key]['user_id'] ."</br>";
        if($authors[$key]['user_login'] == $author){
            return $authors[$key]['user_id'];
        }
    }
    return "not found";
}

/*
*/
function createCategory($catName,$catSlug,$catDescription){
    global $username, $password,$client;
    $res = $client->query('wp.newCategory', '', $username, $password,
        array(
            'name' => $catName,
            'slug' => $catSlug,
            'parent_id' => 0,
            'description' => $catDescription
        )
    );
}
+3

, WordPress (wp-content)

<?php
function attach_wordpress_images($productpicture,$newid)
{
    include('../../../../wp-load.php');
    $upload_dir = wp_upload_dir();
    $dirr = $upload_dir['path'].'/';

    $filename = $dirr . $productpicture;                    
    # print "the path is : $filename \n";                    
    # print "Filnamn: $filename \n";                
    $uploads = wp_upload_dir(); // Array of key => value pairs
    # echo $uploads['basedir'] . '<br />';
    $productpicture = str_replace('/uploads','',$productpicture);
    $localfile =  $uploads['basedir'] .'/' .$productpicture;
    #  echo "Local path = $localfile \n";         

    if (!file_exists($filename))
    {
        echo "hittade inte $filename !";
        die ("no image for flaska $id $newid !");                                                   
    }
    if (!copy($filename, $localfile)) 
    {
        wp_delete_post($newid);
        echo  "Failed to copy the file $filename to $localfile ";
        die("Failed to copy the file $filename to $localfile ");
    }

    $wp_filetype = wp_check_filetype(basename($localfile), null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($localfile)),
        'post_content' => '',
        'post_status' => 'inherit'
        );
    $attach_id = wp_insert_attachment( $attachment, $localfile, $newid );

    // you must first include the image.php file
    // for the function wp_generate_attachment_metadata() to work

    require_once(ABSPATH . 'wp-admin/includes/image.php');        
    $attach_data = wp_generate_attachment_metadata( $attach_id, $localfile );
    wp_update_attachment_metadata( $attach_id, $attach_data );  
}
?>
+1

metaWeblog.newMediaObject , ( metaWeblog.newPost).

metaWeblog.editPost, 401, ,

// Use wp.editPost to edit post types other than post and page.
if ( ! in_array( $postdata[ 'post_type' ], array( 'post', 'page' ) ) )
    return new IXR_Error( 401, __( 'Invalid post type' ) );

wp.editPost, :

$blog_id        = (int) $args[0];
$username       = $args[1];
$password       = $args[2];
$post_id        = (int) $args[3];
$content_struct = $args[4];

, newMediaObject :

$status = $rpc->query(
    'metaWeblog.newMediaObject',
    $postID,
    WP_USERNAME,
    WP_PASSWORD,
    $data
);
$response = $rpc->getResponse();
if( isset($response['id']) ) {
    // ATTACH IMAGE TO POST
    $image['post_parent'] = $postID;
    if( !$rpc->query('wp.editPost', '1', WP_USERNAME, WP_PASSWORD, $response['id'], $image)) {
        die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() );
    }
    echo 'image: ' . $rpc->getResponse();

    // SET FEATURED IMAGE
    $updatePost['custom_fields'] = array( array( 'key' => '_thumbnail_id', 'value' => $response['id'] ) );
    if( !$rpc->query( 'metaWeblog.editPost', $postID, WP_USERNAME, WP_PASSWORD, $updatePost, $publishBool ) ) {
        die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() );
    }
    echo 'update: ' . $rpc->getResponse();
}

Incutio XML-RPC PHP , , . >

+1

. , , Wordpress, . , :

, , - . attach_uploads(), , Wordpress , xml-rpc. - , / . , , , wordpress. , URL- html. - danieru.com

, , , , .

0
source

As with Wordpress 3.5, newmediaobject now recognizes the hack semi-automatically.

no more hacking the -wp-xmlrpc-server.php class.

Instead, your xml-rpc client should send the message number of the variable variable post_id. (It used to be just a "post" variable)

Hope someone helps.

0
source

All Articles