Override wp_unique_filename

How do you pass a callback parameter to a WordPress function?

wp_unique_filename takes 3 parameters ($dir, $filename, and $unique_filename_callback = null). I can’t for the life of me figure out how to pass $unique_filename_callback.

Read More

I’ve tried both add_action and add_filter, each with 10/3

add_action( 'wp_unique_filename', 'my_unique_filename', 10, 3 );
add_filter( 'wp_unique_filename', 'my_unique_filename', 10, 3 );

And then

function my_unique_filename( $dir, $filename, my_unique_filename_cb ){
}
function my_unique_filename_c(){
}

No matter what I put for that this parameter, I get a parse error that it’s expecting a variable. I’ve tried:

my_unique_filename_cb
'my_unique_filename_cb'
my_unique_filename_cb()
'my_unique_filename_cb()'

UPDATE

I’m thinking it needs to be passed as an override to wp_handle_upload which takes an array of overrides, extracts it, and passes $unique_filename_callback as an argument later in the function. In that case, how can I pass my function as a parameter in an array (if this is the solution):

function my_wp_handle_upload( $file, array( 'unique_filename_callback' => myfunction ) ){
  //Which would then extract unique_filename_callback to $unique_filename_callback
  //and pass it to wp_unique_filename as the third parameter
}

Related posts

Leave a Reply

1 comment

  1. wp_unique_filename() checks if a callback function is specified, exists and is callable. Args passed are $dir, $name, and $ext. Here’s a (useless) example:

    function my_unique_filename_function( $dir = '', $filename = 'bar.exe' )
    {
        echo wp_unique_filename( $dir, $filename, 'my_unique_filename_callback' );
    }
    
    function my_unique_filename_callback( $dir, $name, $ext )
    {
        return $name . $ext;
    }
    
    my_unique_filename_function(); // echoes bar.exe
    my_unique_filename_function( '', 'qux.gif' ); // echoes qux.gif
    

    Specifying a custom callback for wp_unique_filename() used by wp_handle_upload() (adapted Codex example):

    $uploadedfile = $_FILES['file'];
    $upload_overrides = array( 'unique_filename_callback' => 'my_unique_filename_callback' );
    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
    if ( $movefile ) {
        echo "File is valid, and was successfully uploaded.";
        var_dump( $movefile);
    } else {
        echo "Possible file upload attack!";
    }