I'm building a way to upload multiple files for an announcement custom post type on the front end. My function here uploads any number of files succesfully so I can see them under "Media" in WordPress... attached to the post.
I need to be able to store the url of the file in a custom field. When I use update_post_meta
... it only updates the values for the last loop/file in my foreach loop below. I can't figure out why?
update_post_meta()
says it "Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure. It also returns false if the value submitted is the same as the value that is already in the database." http://codex.wordpress.org/Function_Reference/update_post_meta
See my comments in the code for where things are happening.
Any ideas? Thanks!
akpsi_insert_attachment( $announcement_id, 'wpcf-announcement_attached_file' );
function akpsi_insert_attachment( $post_id, $post_meta ) {
if ( $_FILES['announcement_upload'] ) {
$files = $_FILES['announcement_upload'];
foreach ( $files['name'] as $key => $value ) {
if ( $files['name'][$key] ) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array( "announcement_upload" => $file );
foreach ( $_FILES as $file_key => $array ) {
// check to make sure its a successful upload
if ($_FILES[$file_key] !== UPLOAD_ERR_OK) __return_false();
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
require_once( ABSPATH . "wp-admin" . '/includes/file.php' );
require_once( ABSPATH . "wp-admin" . '/includes/media.php' );
// successfully uploads any file on each loop
$attach_id = media_handle_upload( $file_key, $post_id );
// this is only updating post meta once, and only the last loop/file.
$attach_url = wp_get_attachment_url( $attach_id );
$postmeta_updated = update_post_meta( $post_id, $post_meta, $attach_url );
// test to see what it gives me on each loop...
// ex: gives me 'int(777)' for first loop/file, 'bool(true)' for second loop/file, 'bool(true)' for third loop/file
var_dump( $postmeta_updated );
}
}
}
}
}