Summery Summery
Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload().
Syntax Syntax
Parameters Parameters
- $file_array
-
(Required) Array similar to a
$_FILESupload array. - $post_id
-
(Required) The post ID the media is associated with.
- $desc
-
(Optional) Description of the side-loaded file.
Default value: null
- $post_data
-
(Optional) Post data to override.
Default value: array()
Return Return
(int|object) The ID of the attachment or a WP_Error on failure.
Source Source
File: wp-admin/includes/media.php
wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
}
return $attachment_id;
}
/**
* Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload().
*
* @since 2.6.0
* @since 5.3.0 The `$post_id` parameter was made optional.
*
* @param array $file_array Array similar to a `$_FILES` upload array.
* @param int $post_id Optional. The post ID the media is associated with.
* @param string $desc Optional. Description of the side-loaded file. Default null.
* @param array $post_data Optional. Post data to override. Default empty array.
* @return int|WP_Error The ID of the attachment or a WP_Error on failure.
*/
function media_handle_sideload( $file_array, $post_id = 0, $desc = null, $post_data = array() ) {
$overrides = array( 'test_form' => false );
$time = current_time( 'mysql' );
$post = get_post( $post_id );
if ( $post ) {
if ( substr( $post->post_date, 0, 4 ) > 0 ) {
$time = $post->post_date;
}
}
$file = wp_handle_sideload( $file_array, $overrides, $time );
if ( isset( $file['error'] ) ) {
return new WP_Error( 'upload_error', $file['error'] );
}
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) );
$content = '';
// Use image exif/iptc data for title and caption defaults if possible.
$image_meta = wp_read_image_metadata( $file );
if ( $image_meta ) {
if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$title = $image_meta['title'];
}
if ( trim( $image_meta['caption'] ) ) {
$content = $image_meta['caption'];
}
}
if ( isset( $desc ) ) {
$title = $desc;
}
Advertisement
Changelog Changelog
| Version | Description |
|---|---|
| 2.6.0 | Introduced. |