将媒体文件从外部URL上传到WordPress媒体库

时间:2014-10-19 13:31:46

标签: wordpress-plugin wordpress

我想从外部网址将文件上传到WordPress媒体库(这对所有帖子/页面都是通用的)。我想要获得的返回值是附件ID,以便将它们注入短代码(例如img)。

我尝试使用IMEDIA_HANDLE_SIDELOAD,但我迷失了$ _FILES设置。

但是,我不确定参数:

  • 这是正确的功能吗?
  • 我应该在代码(aFile)中放置我想要下载的URL吗?
  • 什么是" tmp_name"和"名称"?

请参阅我的代码:

    // my params
    $post_id = 0; // is this what makes it common to all posts/pages?
    $url = 'www.some_external_url.com/blabla.png';

    // example from some forum
    $filepath = '/relative/path/to/file.jpg';
    $wp_filetype = wp_check_filetype( basename( $filepath ), null );
    $aFile["name"] = basename( $filepath );
    $aFile["type"] = $wp_filetype;
    $afile["tmp_name"] = $filepath;

    $attach_id = $media_handle_sideload( $aFile, $post_id, 'sometitle' );

1 个答案:

答案 0 :(得分:10)

解决方案:

private function _uploadImageToMediaLibrary($postID, $url, $alt = "blabla") {

    require_once("../sites/$this->_wpFolder/wp-load.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/image.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/file.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/media.php");

    $tmp = download_url( $url );
    $desc = $alt;
    $file_array = array();

    // Set variables for storage
    // fix file filename for query strings
    preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
    $file_array['name'] = basename($matches[0]);
    $file_array['tmp_name'] = $tmp;

    // If error storing temporarily, unlink
    if ( is_wp_error( $tmp ) ) {
        @unlink($file_array['tmp_name']);
        $file_array['tmp_name'] = '';
    }

    // do the validation and storage stuff
    $id = media_handle_sideload( $file_array, $postID, $desc);

    // If error storing permanently, unlink
    if ( is_wp_error($id) ) {
        @unlink($file_array['tmp_name']);
        return $id;
    }

    return $id;
}