将图像附加到Wordpress XMLRPC中的帖子

sim*_*314 6 wordpress xml-rpc

我正在使用XMLRPC来发布Wordpress的帖子.我在发布缩略图时遇到问题,在调试wordpress代码后,我发现我的问题是由于图像没有附加到帖子这一事实引起的.我必须这样做而不需要修补wordpress或使用PHP,只需要使用XMLRPC.

我可以上传图片并获取图片的ID.让我感到困惑的另一点是你如何将图像附加到你尚未发布的帖子,因为你等待图片上传?我应该上传图片然后发布,然后使用图片ID和帖子ID对图像元数据做更新?

编辑:wordpress中有问题的代码就是这个检查

if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
Run Code Online (Sandbox Code Playgroud)

我的假设是它失败了,因为图像是Unattached,如果我修复该代码一切都很好,但我无法修补我的应用程序用户的WP(所以这不是一个解决方案)

sim*_*314 8

是的,可以这样做,如果Wordpress版本是3.5或更高,当使用代码上传文件/图像时,您可以设置post_id.我用于特色图片的新帖子的流程如下:

  1. 使用newPost函数并发布没有特色图像的内容,并将发布设置为false,记录由此返回的post_id

  2. 上传图片并将post_id设置为刚刚发布的帖子的id,记录image_id

  3. 完成后编辑帖子并将wp_post_thumbnail设置为等于刚刚上传的image_id,并将发布设置为true(如果需要)

重要提示:mime类型很重要,它必须是"image/jpg"或"image/png",请参阅文档,如果mime类型像"jpg"那样附加将失败.

提示:对于调试,如果你从wordpress得到一般错误,你无法弄清楚为什么你可以检查wordpress代码甚至编辑它,添加调试/跟踪调用,希望你能找出原因.

这是包含类别,图像和标签的帖子的示例.它需要class-IXR.php
https://github.com/WordPress/WordPress/blob/master/wp-includes/class-IXR.php
和mime_content_type函数
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);
Run Code Online (Sandbox Code Playgroud)