该函数在媒体库中插入一个附件。函数与wp_update_attachment_metadata() 和wp_generate_attachment_metadata()联合使用。返回wp_posts表格所创建条目的编号。


This function inserts an attachment into the media library. The function should be used in conjunction with wp_update_attachment_metadata() and wp_generate_attachment_metadata(). It returns the ID of the entry created in the wp_posts table.

This function is part of the low-level API used by WordPress for handling attachments. To perform the entire attachment upload and insertion process at once, you will want to use media_handle_upload() instead in most cases.

wp_insert_attachment() 描述


 <?php wp_insert_attachment$attachment$filename$parent_post_id ); ?> 

wp_insert_attachment() 用法



(array) (必填) Array of data about the attachment that will be written into the wp_posts table of the database. Must contain at a minimum the keys post_title, post_content (the value for this key should be the empty string), post_status and post_mime_type.

默认值: None


(string) (可选) Location of the file on the server. Use absolute path and not the URI of the file. The file MUST be on the uploads directory. See wp_upload_dir()

默认值: false


(int) (可选) Attachments may be associated with a parent post or page. Specify the parent's post ID, or 0 if unattached.

默认值: 0

wp_insert_attachment() 参数


Returns the resulting post ID (int) on success or 0 (int) on failure.

wp_insert_attachment() 返回值


wp_insert_attachment() 函数的代码位于 wp-includes/post.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
 * Insert an attachment.
 * If you set the 'ID' in the $args parameter, it will mean that you are
 * updating and attempt to update the attachment. You can also set the
 * attachment name or title by setting the key 'post_name' or 'post_title'.
 * You can set the dates for the attachment manually by setting the 'post_date'
 * and 'post_date_gmt' keys' values.
 * By default, the comments will use the default settings for whether the
 * comments are allowed. You can close them manually or keep them open by
 * setting the value for the 'comment_status' key.
 * @since 2.0.0
 * @see wp_insert_post()
 * @param string|array $args   Arguments for inserting an attachment.
 * @param string       $file   Optional. Filename.
 * @param int          $parent Optional. Parent post ID.
 * @return int Attachment ID.
function wp_insert_attachment( $args, $file = false, $parent = 0 ) {
	$defaults = array(
		'file'        => $file,
		'post_parent' => 0

	$data = wp_parse_args( $args, $defaults );

	if ( ! empty( $parent ) ) {
		$data['post_parent'] = $parent;

	$data['post_type'] = 'attachment';

	return wp_insert_post( $data );

wp_insert_attachment() 源文件