";
// Uploaded files
if ( ! empty( $meta ) )
{
$html .= "
{$i18n_msg}
";
$html .= '';
foreach ( $meta as $attachment_id )
{
$attachment = wp_get_attachment_link( $attachment_id );
$html .= "- {$attachment} ({$i18n_delete})
";
}
$html .= '
';
}
// Show form upload
$html .= "
{$i18n_title}
";
return $html;
}
/**
* Save file field
*
* @param mixed $new
* @param mixed $old
* @param int $post_id
* @param array $field
*/
static function save( $new, $old, $post_id, $field )
{
$name = $field['id'];
if ( empty( $_FILES[ $name ] ) )
return;
$files = self::fix_file_array( $_FILES[ $name ] );
foreach ( $files as $file_item )
{
$file = wp_handle_upload( $file_item, array( 'test_form' => false ) );
if ( ! isset( $file['file'] ) )
continue;
$file_name = $file['file'];
$attachment = array(
'post_mime_type' => $file['type'],
'guid' => $file['url'],
'post_parent' => $post_id,
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_name ) ),
'post_content' => ''
);
$id = wp_insert_attachment( $attachment, $file_name, $post_id );
if ( ! is_wp_error( $id ) )
{
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file_name ) );
// Save file ID in meta field
add_post_meta( $post_id, $name, $id, false );
}
}
}
/**
* Fixes the odd indexing of multiple file uploads from the format:
* $_FILES['field']['key']['index']
* To the more standard and appropriate:
* $_FILES['field']['index']['key']
*
* @param array $files
*
* @return array
*/
static function fix_file_array( $files )
{
$output = array();
foreach ( $files as $key => $list )
{
foreach ( $list as $index => $value )
{
$output[$index][$key] = $value;
}
}
return $output;
}
}
}