Attach image to post in Wordpress XMLRPC

后端 未结 3 1131
时光说笑
时光说笑 2021-01-18 01:58

I am using XMLRPC to do posts to Wordpress. I am having issues posting thumbnails, after debugging wordpress code I see that my issue is caused by the fact that the image is

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-18 02:26

    Yes it is possible to do it, if Wordpress version is 3.5 or greater,when using the code for uploading file/image you can set the post_id. The flow I used for new posts with featured images is like this:

    1. use the newPost function and post the content without the featured image and also set publish to false, record the post_id returned by this

    2. upload the image and set the post_id to the id of the post just posted, record the image_id

    3. when done edit the post and set the wp_post_thumbnail equal to the image_id you just uploaded and also set publish to true(if needed)

    Important: The mime type is important, it must be "image/jpg" or "image/png" please see documentation, if mime type is worng like "jpg" attaching will fail.

    Tip: For debugging, if you get a generic error from wordpress and you can't figure out why you can check the wordpress code and even edit it, adding debugging/tracing calls and hopefully you can figure out the cause.

    This is an example of a post with category, image and tags. It requires class-IXR.php
    https://github.com/WordPress/WordPress/blob/master/wp-includes/class-IXR.php
    and mime_content_type function
    https://github.com/caiofior/storebaby/blob/master/magmi/plugins/extra/general/socialnotify/wp/mimetype.php

            $client = new IXR_Client($url);
            $content = array(
                'post_status' => 'draft',
                'post_type' => 'post',
                'post_title' => 'Title',
                'post_content' => 'Message',
                 // categories ids
                'terms' => array('category' => array(3))
            );
            $params = array(0, $username, $password, $content);
            $client->query('wp.newPost', $params);
            $post_id = $client->getResponse();
    
            $content = array(
                'name' => basename('/var/www/sb/img.jpeg'),
                'type' => mime_content_type('/var/www/sb/img.jpeg'),
                'bits' => new IXR_Base64(file_get_contents('/var/www/sb/img.jpeg')),
                true
            );
            $client->query('metaWeblog.newMediaObject', 1, $username, $password, $content);
            $media = $client->getResponse();
            $content = array(
                'post_status' => 'publish',
                // Tags
                'mt_keywords' => 'tag1, tag2, tag3',
                'wp_post_thumbnail' => $media['id']
            );
            $client->query('metaWeblog.editPost', $post_id, $username, $password, $content, true);
    

提交回复
热议问题