钩子文档

upload_dir

💡 云策文档标注

概述

upload_dir 是一个 WordPress 过滤器钩子,用于修改上传目录的路径和 URL 数据。它允许开发者自定义文件上传的位置,通过 wp_upload_dir() 函数在核心中应用这些更改。

关键要点

  • upload_dir 钩子接收一个数组参数 $uploads,包含上传目录的路径、URL、子目录等信息。
  • 主要参数包括 path(基础目录和子目录路径)、url(基础 URL 和子目录 URL)、subdir(如果启用年月文件夹选项的子目录)、basedir(无子目录的路径)、baseurl(无子目录的 URL)和 error(错误信息或 false)。
  • 此钩子常用于插件开发中,通过 add_filter 添加自定义函数来动态调整上传目录,例如基于文件类型或用户设置。

代码示例

add_filter('upload_dir', 'awesome_wallpaper_dir');

function awesome_wallpaper_dir( $param ){
    $mydir = '/awesome';

    $param['path'] = $param['path'] . $mydir;
    $param['url'] = $param['url'] . $mydir;

    return $param;
}

注意事项

  • 在类中使用时,钩子应添加为数组形式,例如 add_filter( 'upload_dir', array( $this, 'awesome_wallpaper_dir' ) )。
  • 结合 wp_handle_upload_prefilter 钩子,可以根据上传的文件动态决定目标目录,增强灵活性。

📄 原文内容

Filters the uploads directory data.

Parameters

$uploadsarray
Array of information about the upload directory.

  • path string
    Base directory and subdirectory or full path to upload directory.
  • url string
    Base URL and subdirectory or absolute URL to upload directory.
  • subdir string
    Subdirectory if uploads use year/month folders option is on.
  • basedir string
    Path without subdir.
  • baseurl string
    URL path without subdir.
  • error string|false
    False or error message.

More Information

This hook allows you to change the directory where files are uploaded to. The keys and values in the array are used by the wp_upload_dir()  function in wordpress core, which is doing the work

Source

$uploads = apply_filters( 'upload_dir', $cache[ $key ] );

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    This goes into your plugin.

    add_filter('upload_dir', 'awesome_wallpaper_dir');
    
    function awesome_wallpaper_dir( $param ){
        $mydir = '/awesome';
    
        $param['path'] = $param['path'] . $mydir;
        $param['url'] = $param['url'] . $mydir;
    
        return $param;
    }

    If your plugin is written as a class, you’ll want to hook to it like this:

    add_filter( 'upload_dir', array( $this, 'awesome_wallpaper_dir' ) );

    Using this, in conjunction with the wp_handle_upload_prefilter, you can dynamically determine which directory to upload to, based on the files you upload.