Home › Forums › General Issues › Force an Image/File upload to a particular directory › Reply To: Force an Image/File upload to a particular directory
To update the record…
(1)
The “Renaming” part in the following successfully renames a file to a username, retaining the file extension – but only if a valid user ID is supplied as $userid
(hard-coded here as $userid=2
)…
// Filter entry, cf. https://wordpress.stackexchange.com/questions/168790/how-to-get-profile-user-id-when-uploading-image-via-media-uploader-on-profile-pa
add_filter('wp_handle_upload_prefilter', 'my_pre_upload', 2, 2);
// param 1: filter
// param 2: function to execute
// param 3: priority, eg 10
// param 4: number of arguments, eg 2
// pass the $userid as argument to your function
function my_pre_upload($file, $userid=2){
// if no user specified, get $current_user
$userid = $userid ?: get_current_user_id();
$user = get_userdata( $userid );
// 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;
// Return
return $file;
}
Therefore, the question becomes (still), at what point can I access user_id
such that I can pass it through add_filter
?
(2)
So, I am experimenting with whether I can set the user ID as a variable at the time the ACF field is loaded…
// Get and remember User ID when field is loaded??
function user_avatar_filter( $field ) {
$myuserid = $_GET['user_id'];
echo '<pre>load_field: GET user_id is '.$myuserid.'</pre>';
// Important: return the field
return $field;
}
add_filter('acf/load_field/key=field_6140a6da30a17', 'user_avatar_filter');
For test, that code successfully echos out, to the ACF field’s part of the Edit User admin, the correct user ID based on whose Edit User page we are viewing.
So, can that somehow be passed to my_pre_upload()
as parameter $userid
… ?
I haven’t managed it, but I don’t know whether that’s down to a) my poor understanding of global/local variable context or b) that this still isn’t the way this works.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.