函数文档

wp_handle_sideload()

💡 云策文档标注

概述

wp_handle_sideload() 是 _wp_handle_upload() 的包装函数,用于处理从远程服务器下载或非标准上传的文件,将其移动到 WordPress 上传目录。它传递 'wp_handle_sideload' 动作,并允许通过覆盖参数自定义处理行为。

关键要点

  • 函数是 _wp_handle_upload() 的包装器,专门用于处理侧载文件(如通过 download_url() 下载的文件)。
  • 参数 $file 必须是 $_FILES 数组的单个元素引用,包含 name、type、tmp_name、size、error 等键。
  • 参数 $overrides 可选,可覆盖默认变量,如 test_form、test_size、mimes、unique_filename_callback 等。
  • 参数 $time 可选,指定时间格式 'yyyy/mm',用于组织上传目录。
  • 返回数组包含文件路径、URL 和类型等信息,与 _wp_handle_upload() 一致。
  • 常用于媒体处理,如 media_handle_sideload() 和 WP_REST_Attachments_Controller。

代码示例

// 下载 WordPress 徽标并侧载到上传目录
require_once( ABSPATH . 'wp-admin/includes/file.php' );
$url = 'https://s.w.org/style/images/wp-header-logo.png';
$temp_file = download_url( $url, 5 );

if ( ! is_wp_error( $temp_file ) ) {
    $file = array(
        'name'     => basename($url),
        'type'     => 'image/png',
        'tmp_name' => $temp_file,
        'error'    => 0,
        'size'     => filesize( $temp_file ),
    );
    $overrides = array(
        'test_form' => false,
        'test_size' => true,
        'test_upload' => true,
    );
    $results = wp_handle_sideload( $file, $overrides );
    if ( empty( $results['error'] ) ) {
        $filename = $results['file'];
        $local_url = $results['url'];
        $type = $results['type'];
    }
}

注意事项

  • 调用时需确保 $file 参数格式正确,模拟 $_FILES 数组结构。
  • 使用 unique_filename_callback 回调函数可自定义文件名生成逻辑。
  • 返回数组包含 'url'、'type'、'file' 等键,用于后续文件处理。
  • 从 WordPress 2.6.0 版本引入,是处理非标准上传场景的核心函数。

📄 原文内容

Wrapper for _wp_handle_upload() .

Description

Passes the ‘wp_handle_sideload’ action.

See also

Parameters

$filearrayrequired
Reference to a single element of $_FILES.
Call the function once for each uploaded file.
See _wp_handle_upload() for accepted values.

More Arguments from _wp_handle_upload( … $file )

Reference to a single element from $_FILES. Call the function once for each uploaded file.

  • name string
    The original name of the file on the client machine.
  • type string
    The mime type of the file, if the browser provided this information.
  • tmp_name string
    The temporary filename of the file in which the uploaded file was stored on the server.
  • size int
    The size, in bytes, of the uploaded file.
  • error int
    The error code associated with this file upload.

$overridesarray|falseoptional
An associative array of names => values to override default variables.
See _wp_handle_upload() for accepted values.

More Arguments from _wp_handle_upload( … $overrides )

An array of override parameters for this file, or boolean false if none are provided.

  • upload_error_handler callable
    Function to call when there is an error during the upload process.
    See wp_handle_upload_error().
  • unique_filename_callback callable
    Function to call when determining a unique file name for the file.
    See wp_unique_filename().
  • upload_error_strings string[]
    The strings that describe the error indicated in $_FILES[{form field}]['error'].
  • test_form bool
    Whether to test that the $_POST['action'] parameter is as expected.
  • test_size bool
    Whether to test that the file size is greater than zero bytes.
  • test_type bool
    Whether to test that the mime type of the file is as expected.
  • mimes string[]
    Array of allowed mime types keyed by their file extension regex.

Default:false

$timestring|nulloptional
Time formatted in 'yyyy/mm'.

Default:null

Return

array See _wp_handle_upload() for return value.

Source

function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
	/*
	 *  $_POST['action'] must be set and its value must equal $overrides['action']
	 *  or this:
	 */
	$action = 'wp_handle_sideload';
	if ( isset( $overrides['action'] ) ) {
		$action = $overrides['action'];
	}

	return _wp_handle_upload( $file, $overrides, $time, $action );
}

Changelog

Version Description
2.6.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Example

    This example uses download_url() to download the logo from wordpress.org and then moves it into the uploads directory.

    // Gives us access to the download_url() and wp_handle_sideload() functions.
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    
    // URL to the WordPress logo.
    $url = 'https://s.w.org/style/images/wp-header-logo.png';
    $timeout_seconds = 5;
    
    // Download file to temp dir.
    $temp_file = download_url( $url, $timeout_seconds );
    
    if ( ! is_wp_error( $temp_file ) ) {
    
    	// Array based on $_FILE as seen in PHP file uploads.
    	$file = array(
    		'name'     => basename($url), // ex: wp-header-logo.png
    		'type'     => 'image/png',
    		'tmp_name' => $temp_file,
    		'error'    => 0,
    		'size'     => filesize( $temp_file ),
    	);
    
    	$overrides = array(
    		/*
    		 * Tells WordPress to not look for the POST form fields that would
    		 * normally be present, default is true, we downloaded the file from
    		 * a remote server, so there will be no form fields.
    		 */
    		'test_form' => false,
    
    		// Setting this to false lets WordPress allow empty files, not recommended.
    		'test_size' => true,
    
    		// A properly uploaded file will pass this test. There should be no reason to override this one.
    		'test_upload' => true, 
    	);
    
    	// Move the temporary file into the uploads directory.
    	$results = wp_handle_sideload( $file, $overrides );
    
    	if ( ! empty( $results['error'] ) ) {
    		// Insert any error handling here.
    	} else {
    		$filename  = $results['file']; // Full path to the file.
    		$local_url = $results['url'];  // URL to the file in the uploads dir.
    		$type      = $results['type']; // MIME type of the file.
    
    		// Perform any actions here based in the above results.
    	}
    }

  2. Skip to note 5 content

    If you want to rename your uploaded file and you use a PHP class it is needed to do the callback like this:

    class My_Class {
    	public function my_custom_upload() {
    		// Getting file information
    		$file = isset( $_FILES ) ? $_FILES : array();
    		
    		// For exemple it is an image
    		$allowed_mimes = array(
    			'jpg|jpeg|jpe'	=> 'image/jpeg',
    			'gif'			=> 'image/gif',
    			'png'			=> 'image/png',
    		);
    
    		$uploaded_file = wp_handle_sideload( $file['image'], array(
    				'test_form' => false,
    				'mimes'		=> $allowed_mimes,
    				'unique_filename_callback' => array( $this, 'rename_uploaded_file' ),
    			)
    		);
    	}
    
    	public static function rename_uploaded_file( $dir, $name, $ext ) {
    		return 'some_string' . $name . $ext;
    	}
    }