phpwordpresswordpress-theming

How to prevent users from uploading the same file twice WordPress


In my WordPress website, the users are uploading the same image file twice and trice, So my site's Disk Space exceeding.

Is there any option to prevent users to upload the same image file again and again.?


Solution

  • I had the same issue. Instead of adding any validation I added following filter hook which replaces the image, if image with same name already exists. Add this code to your functions.php file

    add_filter( 'sanitize_file_name', 'replace_image_if_same_exists', 10, 1 );
    
    function replace_image_if_same_exists( $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;
    }
    

    Hope this helps you.