update_options and unique filenames

I was able to temporarily disable an automatic task of wordpress during a specific file type upload which is nice.
For instance, I changed the usual upload path for the pdf uploads by doing this:

//change the normal path
update_option('upload_path','wp-content/uploads/attachments/'.$id);
//upload the file
$upload = wp_upload_bits($pdffile,null,file_get_contents($pdffile_temp));
//get the standard path back
update_option('upload_path','');

Now I would like to do the same with the “wp unique filename” function that is automatically called by wordpress.
The same way I changed temporarily the path for this specific upload routine, I would like not to rename the file if another one has the same name inside the target folder (I would rather overwrite the old file with the new one instead).

Read More

How could I do that?

Thank you.

Related posts

Leave a Reply

1 comment

  1. Welcome to the lions den

    So you’re willing to get down into the blazing furnace or the lions den and change the upload path. This is so not a good idea without investigating what is happening behind the scenes. I can’t give you a full write up, as there’s so much involved, like filters, options calls, constants, etc. but I can give you one recommendation: Don’t. Do. This. Things like that tend to work for a while. And then suddenly break, as you hit one of the edge cases. And you’ll be left wondering what happened. Callbacks, options, etc. will hide the problem from you and you will spend ages to trace this bug down.

    EDIT

    Don’t hand/hard code such stuff.

    // Get original value
    $temp = get_option( 'upload_path' );
    // Assign custom value
    update_option( 'upload_path', "wp-content/uploads/attachments/{$id}" );
    
    // do custom stuff
    
    // Move old value back in
    update_option( 'upload_path', $temp );
    

    The wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) function takes three arguments. The third is a custom callback and optional. It takes three arguments: $dir, $name, $ext. Just use this one if you need to do this custom.

    • $dir – The first argument from the wp_unique_filename() fn
    • $ext – retrieved via pathinfo() (PHP default fn) – the file extension. In your case if ( 'pdf' === strtolower( $ext ) ).
    • $name – The filename without extension

    The custom callback can also be completely disabled (I don’t know what then happens – maybe the sky falls on your head?). You can do this by simply using the core functions of __return_false, __return_null (or maybe even __return_zero?).