gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:00:32 31 4
gpt4 key购买 nike

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

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

但是,我不确定参数:

  • 这是正确的功能吗?
  • 我应该在代码(aFile)中的哪个位置放置我要下载的 URL?
  • 什么是“tmp_name”和“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' );

    最佳答案

    解决方案:

    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;
    }

    关于wordpress - 将媒体文件从外部 URL 上传到 WordPress 媒体库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451022/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com