I am trying to limit file upload size on my site and using the following code (which works fine):
function limit_upload_size( $file ) {
// Set the desired file size limit
$file_size_limit = 1024; // 1MB in KB
// exclude admins
if ( ! current_user_can( 'manage_options' ) ) {
$current_size = $file['size'];
$current_size = $current_size / 1024; //get size in KB
if ( $current_size > $file_size_limit ) {
$file['error'] = sprintf( __( 'ERROR: File size limit is %d KB.' ), $file_size_limit );
}
}
return $file;
}
add_filter ( 'wp_handle_upload_prefilter', 'limit_upload_size', 10, 1 );
The only problem I've encountered is that the error message doesn't display. When I change
$file['error'] = sprintf( __( 'ERROR: File size limit is %d KB.' ), $file_size_limit );
to
$file['error'] = sprintf( __e( 'ERROR: File size limit is %d KB.' ), $file_size_limit );
I see the following error message instead: Error #-200: HTTP Error instead of the custom error message.
What is wrong with this code?
Thanks in advance!
That's because __()
returns the translated text, while _e()
displays/echos it. And as you are inside sprintf()
function, you need the returned translated text, not display it to the screen.
_e() codex reference, __() codex reference
Thanks.