WordPress overwrite old uploaded file

how do I set WordPress to overwrite files when uploading a file with the same name as a previously uploaded file? By default, WordPress changes the file name. If I have a file uploaded as image1.png and the try to upload a new one with same file name, the second file will be name image11.png. I want WordPress to replace the old file with the new one. Is this possible?

Related posts

Leave a Reply

1 comment

  1. Adding the following to your functions.php file should work:

    add_filter( 'sanitize_file_name', 'filename_filter_wpse_28439', 10, 1 );
    
    function filename_filter_wpse_28439( $name ) 
    {
        $args = array(
            'numberposts'   => -1,
            'post_type'     => 'attachment',
            'meta_query' => array(
                    array( 
                        'key' => '_wp_attached_file',
                        'value' => $name,
                        'compare' => 'LIKE'
                    )
                )
        );
        $attachments_to_remove = get_posts( $args );
    
        foreach( $attachments_to_remove as $attach )
            wp_delete_attachment( $attach->ID, true );
    
        return $name;
    }
    

    With the above if you upload a file that is already uploaded, it will overwrite that image. The above was sourced from here, but tested on WordPress 3.9.2