我自己想出来的,所以我会把答案贴在这里,请注意,原来的答案也可以找到on StackOverflow. 如果mods觉得应该从这里删除并只保留,请继续。我想这两个地方都可能有用。
首先是正确的代码,然后是解释:
// Here we add a new user role, "cliente".
add_role( \'cliente\', \'Cliente\' );
// These are the filters we need to add in order to modify the default upload path.
add_filter(\'wp_handle_upload_prefilter\', \'my_upload_prefilter\');
add_filter(\'wp_handle_upload\', \'my_upload_postfilter\');
function my_upload_prefilter( $file ) {
add_filter(\'upload_dir\', \'custom_upload_dir\');
return $file;
}
function my_upload_postfilter( $fileinfo ) {
remove_filter(\'upload_dir\', \'custom_upload_dir\');
return $fileinfo;
}
function custom_upload_dir( $path ) {
// When uploading, the file gets sent to upload_async.php, so we need to take the referral page in order to be able to get the user_id we need. We then take the query string, pass it through parse_str and store it in a $query_array. Took me a while to figure it out, but now it works like a charm.
$actual_page = $_SERVER[\'HTTP_REFERER\'];
parse_str( parse_url($actual_page, PHP_URL_QUERY), $query_array );
// Check if we are uploading from the user-edit.php page.
if ( strpos($actual_page, \'user-edit.php\') ) {
// Set the role we want to change the path for.
$role_to_check = \'cliente\';
// Get a bunch of user info for later use
$user_id = filter_var( $query_array[\'user_id\'], FILTER_SANITIZE_NUMBER_INT );
$meta = get_user_meta( $user_id );
$roles = unserialize( $meta[\'wp_capabilities\'][0] );
// If we are on the chosen role page, set the $customdir to first_name + last_name
if ( !empty($roles[$role_to_check]) ) {
$customdir = \'/docs/\' . $meta[\'first_name\'][0] . $meta[\'last_name\'][0];
// If there is any error, just return the $path and abort the rest.
if ( !empty( $path[\'error\'] ) ) {
return $path;
}
// Here we set the new $path with the $customdir set above
$new_subdir = $customdir . $path[\'subdir\'];
$path[\'path\'] = str_replace( $path[\'subdir\'], $new_subdir, $path[\'path\'] );
$path[\'url\'] = str_replace( $path[\'subdir\'], $new_subdir, $path[\'url\'] );
$path[\'subdir\'] = $new_subdir;
return $path;
}
} else {
// We are not uploading from user-edit.php, so go ahead as per default.
return $path;
}
}
问题是,通过Ajax上传时,
$pagenow
正确存储
async-upload.php
页面,而不是我们所在的url。我只需要通过php检索推荐页面
$_SERVER[\'HTTP_REFERER\']
(请注意
referer
打字错误的存在是因为http规范中有一个遗留的打字错误,很有趣)。
还请注意,PHP规范不鼓励使用HTTP_REFERER
因为它可能会根据服务器配置产生意外的结果,但在这种情况下,我应该完全控制服务器,所以这应该不是问题。如果您遇到任何问题,我建议您检查一下。
一旦我有了正确的url,我就能够解析它并检查我们是否在user-edit.php
, 如果是的话user_id
从查询字符串开始,然后从那里继续。
我花了一段时间才弄明白,但事后看来,这很容易。
希望将来能帮助别人。