返回介绍

media_handle_upload()

发布于 2017-09-11 01:49:51 字数 8896 浏览 1118 评论 0 收藏 0

media_handle_upload( string $file_id,  int $post_id,  array $post_data = array(),  array $overrides = array('test_form' => false) )

Save a file submitted from a POST request and create an attachment post for it.


description


参数

$file_id

(string) (Required) Index of the $_FILES array that the file was sent. Required.

$post_id

(int) (Required) The post ID of a post to attach the media item to. Required, but can be set to 0, creating a media item that has no relationship to a post.

$post_data

(array) (Optional) Overwrite some of the attachment. Optional.

Default value: array()

$overrides

(array) (Optional) Override the wp_handle_upload() behavior. Optional.

Default value: array('test_form' => false)


返回值

(int|WP_Error) ID of the attachment or a WP_Error object on failure.


源代码

File: wp-admin/includes/media.php

function media_handle_upload($file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false )) {

	$time = current_time('mysql');
	if ( $post = get_post($post_id) ) {
		if ( substr( $post->post_date, 0, 4 ) > 0 )
			$time = $post->post_date;
	}

	$file = wp_handle_upload($_FILES[$file_id], $overrides, $time);

	if ( isset($file['error']) )
		return new WP_Error( 'upload_error', $file['error'] );

	$name = $_FILES[$file_id]['name'];
	$ext  = pathinfo( $name, PATHINFO_EXTENSION );
	$name = wp_basename( $name, ".$ext" );

	$url = $file['url'];
	$type = $file['type'];
	$file = $file['file'];
	$title = sanitize_text_field( $name );
	$content = '';
	$excerpt = '';

	if ( preg_match( '#^audio#', $type ) ) {
		$meta = wp_read_audio_metadata( $file );

		if ( ! empty( $meta['title'] ) ) {
			$title = $meta['title'];
		}

		if ( ! empty( $title ) ) {

			if ( ! empty( $meta['album'] ) && ! empty( $meta['artist'] ) ) {
				/* translators: 1: audio track title, 2: album title, 3: artist name */
				$content .= sprintf( __( '"%1$s" from %2$s by %3$s.' ), $title, $meta['album'], $meta['artist'] );
			} elseif ( ! empty( $meta['album'] ) ) {
				/* translators: 1: audio track title, 2: album title */
				$content .= sprintf( __( '"%1$s" from %2$s.' ), $title, $meta['album'] );
			} elseif ( ! empty( $meta['artist'] ) ) {
				/* translators: 1: audio track title, 2: artist name */
				$content .= sprintf( __( '"%1$s" by %2$s.' ), $title, $meta['artist'] );
			} else {
				/* translators: 1: audio track title */
				$content .= sprintf( __( '"%s".' ), $title );
			}

		} elseif ( ! empty( $meta['album'] ) ) {

			if ( ! empty( $meta['artist'] ) ) {
				/* translators: 1: audio album title, 2: artist name */
				$content .= sprintf( __( '%1$s by %2$s.' ), $meta['album'], $meta['artist'] );
			} else {
				$content .= $meta['album'] . '.';
			}

		} elseif ( ! empty( $meta['artist'] ) ) {

			$content .= $meta['artist'] . '.';

		}

		if ( ! empty( $meta['year'] ) ) {
			/* translators: Audio file track information. 1: Year of audio track release */
			$content .= ' ' . sprintf( __( 'Released: %d.' ), $meta['year'] );
		}

		if ( ! empty( $meta['track_number'] ) ) {
			$track_number = explode( '/', $meta['track_number'] );
			if ( isset( $track_number[1] ) ) {
				/* translators: Audio file track information. 1: Audio track number, 2: Total audio tracks */
				$content .= ' ' . sprintf( __( 'Track %1$s of %2$s.' ), number_format_i18n( $track_number[0] ), number_format_i18n( $track_number[1] ) );
			} else {
				/* translators: Audio file track information. 1: Audio track number */
				$content .= ' ' . sprintf( __( 'Track %1$s.' ), number_format_i18n( $track_number[0] ) );
			}
		}

		if ( ! empty( $meta['genre'] ) ) {
			/* translators: Audio file genre information. 1: Audio genre name */
			$content .= ' ' . sprintf( __( 'Genre: %s.' ), $meta['genre'] );
		}

	// Use image exif/iptc data for title and caption defaults if possible.
	} elseif ( 0 === strpos( $type, 'image/' ) && $image_meta = @wp_read_image_metadata( $file ) ) {
		if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
			$title = $image_meta['title'];
		}

		if ( trim( $image_meta['caption'] ) ) {
			$excerpt = $image_meta['caption'];
		}
	}

	// Construct the attachment array
	$attachment = array_merge( array(
		'post_mime_type' => $type,
		'guid' => $url,
		'post_parent' => $post_id,
		'post_title' => $title,
		'post_content' => $content,
		'post_excerpt' => $excerpt,
	), $post_data );

	// This should never be set as it would then overwrite an existing attachment.
	unset( $attachment['ID'] );

	// Save the data
	$id = wp_insert_attachment($attachment, $file, $post_id);
	if ( !is_wp_error($id) ) {
		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
	}

	return $id;

}

更新日志

Versiondescription
2.5.0Introduced.

相关函数

Uses

  • wp-admin/includes/image.php: wp_read_image_metadata()
  • wp-admin/includes/image.php: wp_generate_attachment_metadata()
  • wp-admin/includes/media.php: wp_read_audio_metadata()
  • wp-admin/includes/file.php: wp_handle_upload()
  • wp-includes/l10n.php: __()
  • wp-includes/formatting.php: wp_basename()
  • wp-includes/formatting.php: sanitize_text_field()
  • wp-includes/formatting.php: sanitize_title()
  • wp-includes/functions.php: number_format_i18n()
  • wp-includes/functions.php: current_time()
  • wp-includes/post.php: wp_insert_attachment()
  • wp-includes/post.php: wp_update_attachment_metadata()
  • wp-includes/post.php: get_post()
  • wp-includes/load.php: is_wp_error()
  • wp-includes/class-wp-error.php: WP_Error::__construct()
  • Show 10 more uses Hide more uses

Used By

  • wp-admin/includes/media.php: wp_media_upload_handler()
  • wp-admin/includes/ajax-actions.php: wp_ajax_upload_attachment()

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 0You must log in to vote on the helpfulness of this note Contributed by Codex

    Upload an attachment from a form on the front end of the site.

    The upload form might look like this:

    
    <form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
    	<input type="file" name="my_image_upload" id="my_image_upload"  multiple="false" />
    	<input type="hidden" name="post_id" id="post_id" value="55" />
    	<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
    	<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
    </form>
    

    The code to save the attachment:

    
    <?php
    
    // Check that the nonce is valid, and the user can edit this post.
    if ( 
    	isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] ) 
    	&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
    	&& current_user_can( 'edit_post', $_POST['post_id'] )
    ) {
    	// The nonce was valid and the user has the capabilities, it is safe to continue.
    
    	// These files need to be included as dependencies when on the front end.
    	require_once( ABSPATH . 'wp-admin/includes/image.php' );
    	require_once( ABSPATH . 'wp-admin/includes/file.php' );
    	require_once( ABSPATH . 'wp-admin/includes/media.php' );
    	
    	// Let WordPress handle the upload.
    	// Remember, 'my_image_upload' is the name of our file input in our form above.
    	$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
    	
    	if ( is_wp_error( $attachment_id ) ) {
    		// There was an error uploading the image.
    	} else {
    		// The image was uploaded successfully!
    	}
    
    } else {
    
    	// The security check failed, maybe show the user an error.
    }
    

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文