tags:

views:

33

answers:

1

I've run into a problem with WordPress 3.0

I preface my image files with an underscore character (_somefile.jpg) to allow me to flag them for specific uses vs images that don't have the underscore.

However, I've just found that the media uploader in WP 3.0 strips these underscores from the file name. At first I thought it was just renaming the wordpress title for the image but I've verified it in FTP and its actually renaming the file itself.

Is there a setting I can toggle via script to disable this filename editing?

+1  A: 

Function sanitize_file_name() in wp-includes/formatting.php, line 681:

$filename = trim($filename, '.-_');

From the function documentation: "Trim period, dash and underscore from beginning and end of filename."

There is a filter run after this trim() named sanitize_file_name. This code will fix your problem (untested):

function preserve_leading_underscore( $filename, $filename_raw ) {
    if( "_" == substr($filename_raw, 0, 1) ) {
        $filename = "_" . $filename;
    }

    return $filename;
}
add_filter('sanitize_file_name', 'preserve_leading_underscore', 10, 2);
Adam Backstrom
Thanks Adam. Just to clarify, I can add this function to my theme's functions.php correct?
Scott B
Alternately, is there a way to change this behavior in the database? That would allow me to simply do it once and not have to have a command running all the time.
Scott B
Yes, you could add it to your functions.php, or you could [create a plugin](http://codex.wordpress.org/Writing_a_Plugin) with this code. Not sure what you mean by "in the database" but this is the intended way to modify WordPress behavior.
Adam Backstrom
I'll add it to functions.php. What I meant by adding it to database is this: If there is a setting (example: preserve_leading_underscore) in the db that determines if this is on or off, I'd prefer just setting that to off rather than adding code that has to process with each request (client and admin).
Scott B
@Adam - Is there a way I can wrap the "add_filter()" statement so that it does not get processed with each and every page load of the website? I just want it to process when its needed, such as when the admin user for the site is uploading an image via media loader. I'd also like to wrap it in an "if wp version >= 3" test if possible.
Scott B
I did this:if($wp_version >= 3){add_filter('sanitize_file_name', 'preserve_leading_underscore', 10, 2);}
Scott B
Update:if($wp_version >= 3 }
Scott B
Sounds good, though I have to wonder if the is_admin() check is [premature optimization](http://c2.com/cgi/wiki?PrematureOptimization).
Adam Backstrom