WordPress函数wp_insert_attachment()通过代码为文章添加附件(图片/文件)

描述:

通过代码为文章添加附件(图片/文件)

用法:

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

参数:

$attachment

(array) (必填) 将写入数据库wp_posts表的附件的数据数组。必须至少包含关键字post_title、post_content(此关键字的值应为空字符串)、post_status和post_mime_type。

默认值: None

$filename

(string) (可选) 文件在服务器上的位置。使用绝对路径而不是文件的URI。文件必须在uploads目录中。请参阅wp_upload_dir()

默认值: false

$parent_post_id

(int) (可选) 附件可能与父邮件或页关联。指定父级的post ID,如果未附加,则指定0。

默认值: 0

源文件:

/**
 * 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 );
}