通过wp_Handle_sideload()将图像上传到媒体库失败

时间:2011-11-25 作者:Anatol

我的基本场景如下:

我的服务器上有一个目录,每隔一段时间就会通过ftp充满图像。我想将这些图像移动到wp upload目录,然后使用将其添加到媒体库wp_insert_attachment(). 我想wp_handle_sideload() 这是正确的函数,但如果为其中一个图像提供绝对路径,则返回错误。

以下是我目前的代码:

function oo_attach_images($images, $id){   

 //$images is an array of anbsolute image paths, $id is the id of a post I want the images to be attached to.

    require_once(ABSPATH . \'/wp-admin/includes/file.php\');
    require_once(ABSPATH . \'/wp-admin/includes/image.php\');

    foreach($images as $image){

        $override = array(\'test_form\' => FALSE);

        $file = wp_handle_sideload($image, $override);

        print_r($file); //returns: Array ( [error] => )

        $attachment = array(
            \'post_mime_type\' => $file[\'type\'],
            \'post_title\' => basename($image),
            \'post_content\' => \' \',
            \'post_status\' => \'inherit\'
        );

        $attach_id = wp_insert_attachment( $attachment, $file[\'file\'], $id );

        $attach_data = wp_generate_attachment_metadata( $attach_id, $file[\'file\'] );
        wp_update_attachment_metadata( $attach_id,  $attach_data );


    }
}
我研究了类似的问题,但其中列出的解决方案似乎都与侧载本身的失败无关。坦率地说,我认为我没有将正确的文件路径传递给wp_handle_sideload(), 但由于它在法典中没有记录,我不知道它可能会得到什么样的输入。有人知道我需要做什么改变才能让这一切顺利吗?

4 个回复
最合适的回答,由SO网友:sanchothefat 整理而成

您的文件数组需要模拟$\\u全局文件,因此您需要使用一些文件输入创建一个虚拟页面,打印或转储$\\u文件的内容,以查看其结构。用数据创建一个类似的变量并传递它wp_handle_sideload().

EDIT:

此答案在撰写本文时是正确的,如果您希望使用wp_handle_sideload(). media_handle_sideload() 允许您同时将媒体连接到帖子。

See @anatol\'s own answer for a full solution.

SO网友:Anatol

这是一段令人惊讶的简单代码,最终实现了它的预期目标:

function oo_attach_images($images, $id){ //$images is an array of image urls, $id is the ID of the post I want the images to be attached to

    require_once(ABSPATH . \'/wp-admin/includes/file.php\');
    require_once(ABSPATH . \'/wp-admin/includes/media.php\');
    require_once(ABSPATH . \'/wp-admin/includes/image.php\');

    foreach($images as $image){

        $array = array( //array to mimic $_FILES
            \'name\' => basename($image), //isolates and outputs the file name from its absolute path
            \'type\' => wp_check_filetype($image), // get mime type of image file
            \'tmp_name\' => $image, //this field passes the actual path to the image
            \'error\' => 0, //normally, this is used to store an error, should the upload fail. but since this isnt actually an instance of $_FILES we can default it to zero here
            \'size\' => filesize($image) //returns image filesize in bytes
        );

        media_handle_sideload($array, $id); //the actual image processing, that is, move to upload directory, generate thumbnails and image sizes and writing into the database happens here
    }
}

SO网友:Charles Jaimet

我使用了Anatol的代码,但在使用HTTP提取图像时遇到了麻烦。要解决此问题,请先使用download\\u url获取图像的本地副本。

了解media\\u handle\\u sideload返回附件id号也很有用,您可以在上载图像后使用该id号显示图像。

foreach($images as $image){
  $tmp_name = download_url( $image ); // get the image and save it locally temporarily
  $array = array(
    \'name\' => basename( $image ),
    \'type\' => \'image/jpeg\',
    \'tmp_name\' => $tmp_name,
    \'error\' => 0,
    \'size\' => filesize( $tmp_name )
  );
  $_image_id = media_handle_sideload($array, $id);
  $_src = wp_get_attachment_url( $_image_id );
  echo \'<img src="\' . $_src . \'" />\';
}

SO网友:Zarar Ansari

try

    { // only need these if performing outside of admin environment
    require_once(ABSPATH . \'wp-admin/includes/media.php\');
    require_once(ABSPATH . \'wp-admin/includes/file.php\');
    require_once(ABSPATH . \'wp-admin/includes/image.php\');

    // example image
    $image = $review[\'image\'];
    // magic sideload image returns an HTML image, not an ID
    $media = media_sideload_image($image, $new_post_id);

    // therefore we must find it so we can set it as featured ID
    if(!empty($media) && !is_wp_error($media)){
        $args = array(
            \'post_type\' => \'attachment\',
            \'posts_per_page\' => -1,
            \'post_status\' => \'any\',
            \'post_parent\' => $new_post_id
        );

        // reference new image to set as featured
        $attachments = get_posts($args);

        if(isset($attachments) && is_array($attachments)){
            foreach($attachments as $attachment){
                // grab source of full size images (so no 300x150 nonsense in path)
                $image = wp_get_attachment_image_src($attachment->ID, \'full\');
                // determine if in the $media image we created, the string of the URL exists
                if(strpos($media, $image[0]) !== false){
                    // if so, we found our image. set it as thumbnail
                    set_post_thumbnail($new_post_id, $attachment->ID);
                    // only want one image
                    break;
                }
            }
        }
    }
      } catch (Exception $e) {
          echo \'Caught exception: \',  $e->getMessage(), "\\n";
      }
结束

相关推荐

404从wp-Content/Uploads/获取图像时

我在获取图像时获得404状态,http仍然包含该图像。图像显示在浏览器中,但404代码中断了一些应用程序。对wp内容/上载/的调用被重定向到。htaccess:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\\.php$ - [L] RewriteRule (.*) /index.php?getfile=$1 [L] </IfModule>&