Metabox with multiple fields added by user and upload box

I’m trying to build system, where user can add as many fields as he needs to the post. I’m using code from this thread. Everythings works fine, except I can’t get my upload working.

Here’s code I’ve added inside foreach loop in dynamic_inner_custom_box() function:

<input class="upload_file" type="text" size="45" id="items[%1$s][picture]" name="items[%1$s][picture]" value="%6$s" />
<input class="upload_button button" type="button" value="Upload File" />
<input class="upload_file_id" type="hidden" id="items[%1$s][picture]_id" name="items[%1$s][picture]_id" value="%6$s" />

The %6$s value is item['picture'] ofc. I don’t understand how this works. There are two fields for upload – .upload_file and .upload_file_id. If I’m correct, I need to add _id to my .upload_file‘s name, and save it as .upload_file_id‘s name. The problem is, when I choose some image from the upload thickbox, it doesn’t put the link in my input field. I’ve been playing for a while now, and I’ve been able to get this link in place by playing with names/id’s but than I couldn’t save the data. What’s incorrect in my code? Do I need to extend somehow save function?

@edit
After changing code to this:

<input class="upload_file" type="text" size="45" id="picture_%1$s" name="picture_%1$s" value="%6$s" />
<input class="upload_button button" type="button" value="Upload File" />
<input class="upload_file_id" type="hidden" id="picture_%1$s_id" name="items[%1$s][picture]" value="%6$s" />

I am finally saving something and I’m able to get attachment link in right place for a moment. When I coose a picture, a link is inserted where it should be, but after saving only some numbers are stored in databse ( attachment ID maybe? ).

1 Answer
1

Here is how I’ve done it. No changes to the save function are needed. I’ve been trying to save data from both fields at once, thats why it didn’t worked.

<input class="upload_file" type="text" size="45" id="picture_%1$s" name="picture_%1$s" value="%6$s" />
<input class="upload_button button" type="button" value="Upload File" />
<input class="upload_file_id" type="hidden" id="picture_%1$s_id" name="items[%1$s][picture]" value="%7$s" />

The value stored in .upload_file_id is attachment ID (%7$s == item['picture']).
The value displayed in .upload_file (%6$s) is wp_get_attachment_image_src like so:

$img = wp_get_attachment_image_src($item['picture']);
$img = $img[0];

And then we set %6$s to be $img. So in database just the attachment ID is stored, and we display link using WordPress function.

Leave a Comment