function save_attachment_meta($post_id, $post, $update){
global $wpdb;
$currentDateTime = date("Y-m-d H:i:s");
// First check if the file appears on the _FILES array
$files = $_FILES['image_field_name'];
$upload_dir = wp_upload_dir();
$post_dirname = $upload_dir['basedir'].'/'.$post->post_title.'_'.$post_id;
$post_dirname = $post_dirname;
$permissions = 0777;
$oldmask = umask(0);
if (!is_dir($post_dirname))
mkdir($post_dirname, $permissions);
umask($oldmask);
chmod($post_dirname, $permissions);
$user_url = $upload_dir['baseurl'].'/'.$post_dirname;
//define('UPLOADS',$user_dirname);
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 ("my_file_upload" => $file);
foreach ($_FILES as $file => $array) {
//echo $user_dirname;
$uploaded = move_uploaded_file($array['tmp_name'],$user_subdirMname.'/'.$array['name']);
$filename = $array['name'];
$msg = '';
if($uploaded != 1){
$msg = "Error uploading file. ";
}else{
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'guid' => $user_url . '/' . str_replace(' ','%20',basename( $filename )),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
if(isset($_GET['id'])):
////code update attactment
else:
////code insert attactment
endif;
$wpdb->query($sql);
$msg = "File upload successful!";
}
}
}
}
}
return $msg;
}
add_action ('save_post', 'save_attachment_meta', 10, 3);