WordPress上传文件存放到不同目录的方法


本文整理自网络,侵删。

有时候将不同类型的文件分门别类存储,似乎比年月目录更有意义。例如幻灯片应该存储在slides目录下,下载文件应该存储在downloads文件夹下。就说幻灯片slideshow,我比较喜欢用自定义文章类型(Custom Post Type)实现,有些幻灯片脚本比较个性,不支持绝对路径,必须用相对路径,然后用base参数设置相对于哪个文件夹,这样幻灯片必须存储在某个特定的文件夹中,年月形式显然不满足要求。所以,我们需要条件化的设置上传目录。

一、为Custom Post Type设置上传目录

假设我要将所有在幻灯片类型的文章中上传的文件存储到/wp-content/uploads/slides文件夹中,将下面的代码放到主题的functions.php中即可

代码如下:
function custom_upload_directory( $uploads ) {
$id = $_REQUEST['post_id'];
$parent = get_post( $id )->post_parent;
if( "post-type" == get_post_type( $id ) || "post-type" == get_post_type( $parent ) ) {
$subdir = 'slides';
$uploads['subdir'] = $subdir;
$uploads['path'] = $uploads['basedir'].DIRECTORY_SEPARATOR.$subdir;
$uploads['url'] = $uploads['baseurl'].'/'.$subdir;
}
return $uploads;
}
add_filter( 'upload_dir', 'custom_upload_directory' );
将post-type替换成自己的自定义文章类型名称,将你要创建的子目录赋值给$subdir。

二、将文件保存到插件目录

下面的代码要用在插件中,文件会保存到插件目录下的uploads文件夹下。

代码如下:

/**
* Change Upload Directory for Custom Post-Type
*
* This will change the upload directory for a custom post-type. Attachments will
* now be uploaded to an "uploads" directory within the folder of your plugin. Make
* sure you swap out "post-type" in the if-statement with the appropriate value...
*/
function custom_upload_directory( $args ) {
$id = $_REQUEST['post_id'];
$parent = get_post( $id )->post_parent;
// Check the post-type of the current post
if( "post-type" == get_post_type( $id ) || "post-type" == get_post_type( $parent ) ) {
$args['path'] = plugin_dir_path(__FILE__) . "uploads";
$args['url'] = plugin_dir_url(__FILE__) . "uploads";
$args['basedir'] = plugin_dir_path(__FILE__) . "uploads";
$args['baseurl'] = plugin_dir_url(__FILE__) . "uploads";
}
return $args;
}
add_filter( 'upload_dir', 'custom_upload_directory' );
如果要以年月形式保存,修改一下代码即可

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...