Support Forum
Support › Meta Box AIO › Dynamic uploaded filenameResolved
Hi,
Is it possible to dynamically rename a file uploaded with the "file "custom field please?
I have red some tips about unique_filename_callback function, but it is beyond my level...
I would like to add a prefix with the username and some text to each uploaded files.
The files are uploaded to a custom folder, you already helped me to do it here:
https://support.metabox.io/topic/file-custom-field-upload-to-dynamic-directory/
Best regards
Hi,
Here is an example to add the text 1234
to the file name:
function my_unique_filename_callback( $dir, $name, $ext ) {
$name = $name . '1234';
return $name . $ext;
}
add_filter( 'rwmb_meta_boxes', 'your_prefix_function_name' );
function your_prefix_function_name( $meta_boxes ) {
$meta_boxes[] = [
'title' => __( 'Post Meta', 'your-text-domain' ),
'id' => 'post-meta',
'fields' => [
[
'name' => __( 'File', 'your-text-domain' ),
'id' => 'file',
'type' => 'file',
'upload_dir' => WP_CONTENT_DIR . '/invoices/',
'unique_filename_callback' => 'my_unique_filename_callback',
],
],
];
return $meta_boxes;
}
Refer to this topic https://stackoverflow.com/questions/27571023/override-wp-unique-filename
Thank you for your support!
Your example works for a text prefix, but I don't know how to add username as a prefix too. Here is my code:
<div>
function my_unique_filename_callback( $dir, $name, $ext ) {
$name = 'emargements_' . $name;
return $name . $ext;
}
add_filter( 'rwmb_meta_boxes', 'metabox_file_upload_formateurs_emargements' );
function metabox_file_upload_formateurs_emargements( $meta_boxes ) {
$prefix = '';
$current_user = wp_get_current_user();
$user_login = $current_user->user_login;
$meta_boxes[] = [
'title' => __( 'Documents formateurs', 'your-text-domain' ),
'id' => 'documents-formateurs',
'fields' => [
[
'id' => $prefix . 'file_docformateursemarge',
'name' => __( 'Documents formateurs émargements', 'your-text-domain' ),
'type' => 'file',
'upload_dir' => ABSPATH . 'myfile/' . $user_login . '/emargements',
'unique_filename_callback' => 'my_unique_filename_callback',
],
],
];
return $meta_boxes;
}
</div>
I can't edit, sorry for the code.
Hi,
You can use the function to get the user login name as the code that registers the meta box to add the user name to the file name.
function my_unique_filename_callback( $dir, $name, $ext ) {
$current_user = wp_get_current_user();
$user_login = $current_user->user_login;
$name = 'emargements_' . $user_login . '_' . $name;
return $name . $ext;
}
It's ok, thank you again!
Last question... each time I send a file wordpress creates a new post with attached file. Is it possible to skip this?
And the the uploaded file is renamed with the extension. myfile.png becomes username_myflie.png.png
The unique_filename_callback parameters are not documented, nor is the return value in https://docs.metabox.io/fields/file/