我在我的functions.php中使用了一段代码,理论上应该改变我的自定义帖子类型的上传位置(保留页面和帖子上传目录相同)
我的自定义帖子类型为“下载”
我的新目录是“ wp-content ”文件夹中名为“下载”的文件夹。
我的 wp-content 目录看起来像这样......
看下面的功能,有什么可以帮助我理解为什么这不起作用?感谢。
add_filter( 'upload_dir', 'my_custom_upload_dir' );
function my_custom_upload_dir( $default_dir ){
global $post;
if ( $post->post_type != 'download' ) {
return $default_dir;
}
/*
* On success, the returned array will have many indices:
* 'path' - base directory and sub directory or full path to upload directory.
* 'url' - base url and sub directory or absolute URL to upload directory.
* 'subdir' - sub directory if uploads use year/month folders option is on.
* 'basedir' - path without subdir.
* 'baseurl' - URL path without subdir.
* 'error' - set to false.
*/
// Adjust settings here
$bdir = 'wp-content';
$subdir = date( 'Y/m' );
$dir = $bdir . $subdir;
$burl = content_url('downloads');
$url = $burl . $subdir;
$custom_dir = array(
'path' => $dir,
'url' => $url,
'subdir' => $subdir,
'basedir' => $bdir,
'baseurl' => $burl
);
return shortcode_atts( $custom_dir, $default_dir );
}
答案 0 :(得分:2)
uploads_dir
过滤器需要另一个实现来成功修改上传目录/路径。
add_filter('wp_handle_upload_prefilter', 'so_8519968_handle_upload_prefilter');
add_filter('wp_handle_upload', 'so_8519968_handle_upload');
function so_8519968_handle_upload_prefilter( $file )
{
add_filter('upload_dir', 'so_8519968_custom_upload_dir');
return $file;
}
function so_8519968_handle_upload( $fileinfo )
{
remove_filter('upload_dir', 'so_8519968_custom_upload_dir');
return $fileinfo;
}
function so_8519968_custom_upload_dir( $path )
{
// Check if uploading from inside a post/page/cpt - if not, default Upload folder is used
$use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
if( !empty( $path['error'] ) || $use_default_dir )
return $path;
// Check if correct post type
$the_post_type = get_post_type( $_REQUEST['post_id'] );
if( 'movies' != $the_post_type )
return $path;
$customdir = '/' . date( 'Y/m' );
//remove default subdir (year/month) and add custom dir INSIDE THE DEFAULT UPLOAD DIR
$path['path'] = str_replace( $path['subdir'], '/downloads' . $customdir, $path['path']);
$path['url'] = str_replace( $path['subdir'], '/downloads' . $customdir, $path['url']);
$path['subdir'] = $customdir;
return $path;
}
这里需要注意的是结构是/wp-content/uploads/downloads/yyyy/mm/filename.ext
。
我认为以下内容会处理/wp-content/downloads/...
,但我无法确定它无效的原因。
$path['path'] = str_replace( 'uploads' . $path['subdir'], 'downloads' . $customdir, $path['path']);
$path['url'] = str_replace( 'uploads' . $path['subdir'], 'downloads' . $customdir, $path['url']);
$path['basedir'] = str_replace( 'uploads', 'downloads', $path['basedir']);
$path['baseurl'] = str_replace( 'uploads', 'downloads', $path['baseurl']);
$path['subdir'] = $customdir;
也许必须在媒体设置,wp-content
中将uploads文件夹设置为http://example.com/wp-admin/options-media.php
,并使函数so_8519968_custom_upload_dir
的前两个条件处理其他上传可能性(直接在媒体库中 - 没有ID的帖子,以及其他帖子类型)。