如果我没弄错的话,那应该是可能的。您要使用media_handle_upload()
, 哪个呼叫wp_handle_upload()
处理文件上载。wp_handle_upload()
on本身不会有帮助,尤其是因为它几乎只是_wp_handle_upload()
. 还没有结束,因为里面_wp_handle_upload()
功能wp_upload_dir()
就是我们找到钩子的地方upload_dir
:
/**
* Filters the uploads directory data.
*
* @since 2.0.0
*
* @param array $uploads Array of upload directory data with keys of \'path\',
* \'url\', \'subdir, \'basedir\', and \'error\'.
*/
$uploads = apply_filters( \'upload_dir\', $cache[ $key ] );
The
upload_dir
过滤器可用于更改上载路径。为此,我们需要一个函数:
function wpse_custom_upload_dir( $dir_data ) {
// $dir_data already you might want to use
$custom_dir = \'custom\';
return [
\'path\' => $dir_data[ \'basedir\' ] . \'/\' . $custom_dir,
\'url\' => $dir_data[ \'url\' ] . \'/\' . $custom_dir,
\'subdir\' => \'/\' . $custom_dir,
\'basedir\' => $dir_data[ \'error\' ],
\'error\' => $dir_data[ \'error\' ],
];
}
然后你可以这样使用它:
// changing the directory
add_filter( \'upload_dir\', \'wpse_custom_upload_dir\' );
// uploading
$upload = media_handle_upload( \'some_upload\', $post_id );
// remove so it doesn\'t apply to all uploads
remove_filter( \'upload_dir\', \'wpse_custom_upload_dir\' );
所有这些或多或少都是示范性的,但我相信你明白其中的道理。有关更多详细信息,请查看我链接的文档页面,在那里您还可以浏览源代码。