php - WordPress custom file upload being overwritten on no file selection

I'm working on a custom theme that allows you to upload multiple images on one page. Since I have multiple file inputs, I use this function in my functions.php file (inside a loop for each file input):

register_setting('hero', 'slider_slide_' . $i . '_image',
function($option) use ($i) {
    if (!empty($_FILES['slider_slide_' . $i . '_image']['tmp_name'])) {
        $_FILES['slider_slide_' . $i . '_image']['name'] = 'slide_' . $i . '.png';
        $urls = wp_handle_upload($_FILES['slider_slide_' . $i . '_image'], array('test_form' => FALSE));
        $temp = $urls['url'];
        return $temp;
    }
    return $option; 
});

The inline function is the only thing I've tried that works for multiple files at a time. Either way, I'm now facing the issue of having my options being overwritten. Once uploaded, the option is set in my database, with the correct link to the image. However, if I change other settings on the page later, since nothing is uploaded, the option is overwritten with a blank string, despite me checking for the file not being empty before updating the option.

Ideally I'd like to allow a user to change anything and everything and check the file upload to check if anything is selected, and if so, upload and update the option.

Only problem is, Wordpress seems to be dealing with the updating of the options...

No errors are being thrown either, so I'm totally stumped right now.

Answer

Solution:

I assume that WP is still receiving your empty file inputs, so you need to return the stored value.

Try something like that.

register_setting('hero', 'slider_slide_' . $i . '_image',
function($value, $option) use ($i) {
    if (empty($_FILES['slider_slide_' . $i . '_image']['tmp_name'])) {
        return get_option($option); 
    }

    $_FILES['slider_slide_' . $i . '_image']['name'] = 'slide_' . $i . '.png';
    $urls = wp_handle_upload($_FILES['slider_slide_' . $i . '_image'], array('test_form' => FALSE));

    return $urls['url'];
});

Another way is to fill 'slider_slide_' . $i . '_image' input with the stored value.

Answer

Solution:

Daniel G. above this answer has pretty much solved it, I had to adjust it a little, but for the sake of anyone else who has this problem, here's the code I used to fix it.

register_setting('hero', 'slider_slide_' . $i . '_image',
    function($option) use ($i) {
        if ($_FILES['slider_slide_' . $i . '_image']['error'] != 0) {
            return get_option('slider_slide_' . $i . '_image');
        }
        $_FILES['slider_slide_' . $i . '_image']['name'] = 'slide_' . $i . '.png';
        $urls = wp_handle_upload($_FILES['slider_slide_' . $i . '_image'],
                array(
                    'test_form' => FALSE,
                    'unique_filename_callback' => 'file_override_overwrite'
                )
        );
        $temp = $urls['url'];
        return $temp;
    }
);

Source