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.
Advertisement
Answer
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.