I have already published this on StackOverflow, but I realised it would be better to post it here instead.
I am using the CMB script (Custom Meta Boxes and Fields for WordPress) for uploading files for different users that have the custom role of cliente
.
I am able to show the fields and make them work (though they only appear when editing a user, and not when creating it, but this is for another question). What I am trying to achieve now is to upload files to different folders for different users.
Here is the code:
// Here we add a new user role, "cliente"
add_role( 'cliente', 'Cliente' );
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 ) {
global $pagenow;
// Check if we are on the user-edit.php page
if ( $pagenow == 'user-edit.php' && isset($_GET['user_id']) ) {
// 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( $_GET['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 = '/' . $meta['first_name'][0] . $meta['last_name'][0];
}
} else {
// Here we are not on the user-edit.php page. This is just a check to prove that WP is not recognizing the correct page, maybe because we are doing an Ajax call when this function is called. Confusing.
$customdir = '/did-not-work';
}
// 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
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
From a few checks I have run it seems like my code does retrieve the user id and the data stored in the db, but it does not detect it when uploading the images. Might this be related to the fact that we are uploading images via Ajax or something like that?
Just to be clear, I don't want the upload based on the current logged in user, but on the user I, as a super-admin, am editing using the edit-user.php page.
Any help would be much appreciated.