How to force Media manager to overwrite files of same name?

Here is something i cooked up which was taken mainly from the plugin Overwrite Uploads but without the extra stuff

add_filter('wp_handle_upload_overrides','noneUniqueFilename');
function noneUniqueFilename($overrides){
    $overrides['test_form'] = false;
    $overrides['unique_filename_callback'] = 'nonUniqueFilenameCallback';
    return $overrides;
}

function nonUniqueFilenameCallback($directory, $name, $extension){
    $filename = $name . strtolower($extension);
    //remove old attachment
    removeOldAttach($filename);

    return $filename;
}

function removeOldAttach($filename){
    $arguments = array(
        'numberposts'   => -1,
        'meta_key'      => '_wp_attached_file',
        'meta_value'    => $filename,
        'post_type'     => 'attachment'
    );
    $Attachments_to_remove = get_posts($arguments);

    foreach($Attachments_to_remove as $a)
        wp_delete_attachment($a->ID, true);
}

Leave a Comment