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;
  • You mean the ID that you were looking at on the page that generated the upload request? I doubt that'll be available automatically; I think you'll have to pass it as an URL parameter with the upload. – Rup Nov 19 '14 at 18:40
  • Yes, I need the ID of the user to whom the profile page belongs which I am editing right now. – benutzerfreund Nov 20 '14 at 13:22
  • What plugin did you use? – ifdion Jan 18 '15 at 0:32
  • I created this PlugIn myself. It is still very crude, so it is definitely not ready for use… – benutzerfreund Jan 19 '15 at 19:39

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;
  • 1
    I can not test this right now, but doesn't returns get_current_user_id() the ID of the user which is currently logged in? Just to make sure: What I need is the ID of the user to whom the profile belongs I am currently editing. Thanks! – benutzerfreund Jan 26 '15 at 17:15
  • What $userid = $userid ?: get_current_user_id(); means is: if $userid has not been provided, use the current user id. If it has been provided as the second parameter, use that one. So you need to call the function in your code as my_pre_upload($file, $userid) where $userid is the id of the user to whom the profile belongs. – tao Jan 26 '15 at 17:19
  • Tried it, and it is as I did afraid: Your code works fine, but it saves the image with the ID of my own user profile when I edit someone else's. Any idea what I can do? (I exactly copied your code in my plugin, only corrected 2 typos.) – benutzerfreund Jan 30 '15 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.