In a function fired from filter wp_handle_upload_prefilter
, how can I utilise a variable obtained from previously firing action edit_user_profile
?
My aim: on user-edit.php
, when user uploads a file (ACF Image), get username of the user who is the subject of the form (not current user) and use that to rename the file.
My current idea:
Using
edit_user_profile
, when Edit User loads, capture the ID to a variable.Feed that into the function fired by
wp_handle_upload_prefilter
, which does the file renaming, so that I can generate the required filename string.
However, I cannot manage to get this working in a way that doesn't throw an error inside the Media picker modal.
Options?:
I'm not sure if my use of global
s is correct. I would prefer this method as it seems simplest.
Anonymous functions and using use
?
Am I totally wrong to infer I can pass them this way, when the upload prefilter is probably focused on an Ajax modal? I assumed passing the variable would still be fine. Does the order matter?
$myuserid = 5; // global scope - set 5 just to test flow
// 1b. WHEN EDIT-USER.PHP LOADS, CAPTURE USER_ID
function custom_user_profile_fields( $profileuser ) {
$myuserid = $_GET['user_id'];
echo '<h1>Foo We are Setting $myuserid to '.$myuserid.'</h1>';
}
// add_action( 'show_user_profile', 'custom_user_profile_fields' );
add_action( 'edit_user_profile', 'custom_user_profile_fields' );
// 2. WHEN TAKING AN UPLOAD, USE USER_ID TO GET OUR DATA & RENAME FILE
// Filter entry, cf. https://wordpress.stackexchange.com/questions/168790/how-to-get-profile-user-id-when-uploading-image-via-media-uploader-on-profile-pa
// p1: filter, p2: function to execute, p3: priority eg 10, p4: number of arguments eg 2
add_filter('wp_handle_upload_prefilter', 'my_pre_upload', 2, 1);
function my_pre_upload($file, $myuserid){ // was function my_pre_upload($file, $myuserid) with 2 arguments{
$user = get_userdata( $myuserid );
// Renaming, cf. https://stackoverflow.com/a/3261107/1375163
$info = pathinfo($file['name']);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($file['name'], $ext);
$file['name'] = $user->user_login . $ext;
// Carry on
return $file;
}