I have a PlugIn which lets a user upload an image to a user profile in the backend. Now I want to access the user id in the uploader to change the filename of the uploaded image.
On the user profile edit page, I get the id via global $profileuser
. But when I access it in a function I added as a filter to wp_handle_upload
, $profileuser is empty.
Any ideas how to get the profile user (not the logged in user) in this case?
This is my code:
add_filter('wp_handle_upload_prefilter', 'my_pre_upload', 2);
function my_pre_upload($file){
// get current user
global $profileuser;
$myAuthorImg = get_userdata( $profileuser->ID );
$myAuthorImg = 'author-' . $myAuthorImg . '.jpg";
$file['name'] = $myAuthorImg
return $file;
}
1 Answer
You need to pass the $profileuser->ID as the second argument when you call your function and define it accordingly:
add_filter('wp_handle_upload_prefilter', 'my_pre_upload', 2, 2);
// (3rd param is priority, 4th is number of args)
// and pass the $userid as argument to your function
function my_pre_upload($file, $userid = false){
// if no user specified, get $current_user
$userid = $userid ?: get_current_user_id();
$user = get_userdata( $userid );
$myAuthorImg = 'author-' . $user->ID . '.jpg";
$file['name'] = $myAuthorImg
return $file;
}