函数文档

wp_insert_attachment()

💡 云策文档标注

概述

wp_insert_attachment() 函数用于在 WordPress 中插入或更新附件。它基于 wp_insert_post() 实现,支持通过参数控制附件属性、父文章关联和错误处理。

关键要点

  • 函数核心是调用 wp_insert_post(),将 post_type 设置为 'attachment' 来处理附件。
  • 参数 $args 为必需,可包含 ID(用于更新)、post_name、post_title、post_date、post_date_gmt、comment_status 等键来设置附件属性。
  • 可选参数包括 $file(文件名)、$parent_post_id(父文章ID)、$wp_error(是否返回 WP_Error)、$fire_after_hooks(是否触发钩子)。
  • 成功时返回附件ID,失败时返回 0 或 WP_Error。
  • 相关函数包括 wp_insert_post()、wp_parse_args(),常用于媒体处理、REST API 和后台管理功能。

代码示例

// 示例:插入附件到父文章ID为37
$attachment = array(
    'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
    'post_mime_type' => $filetype['type'],
    'post_title' => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
    'post_content' => '',
    'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
// 生成元数据并设置特色图像
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( 37, $attach_id );

注意事项

  • 设置 'ID' 参数可更新现有附件,否则插入新附件。
  • 注释状态默认使用设置,可通过 comment_status 手动控制。
  • 媒体上传推荐使用 media_handle_upload() 函数。
  • 插入后常需调用 wp_generate_attachment_metadata() 和 set_post_thumbnail() 处理元数据和特色图像。

📄 原文内容

Inserts an attachment.

Description

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.

See also

Parameters

$argsstring|arrayrequired
Arguments for inserting an attachment.
$filestring|falseoptional
Filename.

Default:false

$parent_post_idintoptional
Parent post ID or 0 for no parent. Default 0.
$wp_errorbooloptional
Whether to return a WP_Error on failure.

Default:false

$fire_after_hooksbooloptional
Whether to fire the after insert hooks.

Default:true

Return

int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.

Source

function wp_insert_attachment( $args, $file = false, $parent_post_id = 0, $wp_error = false, $fire_after_hooks = true ) {
	$defaults = array(
		'file'        => $file,
		'post_parent' => 0,
	);

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

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

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

	return wp_insert_post( $data, $wp_error, $fire_after_hooks );
}

Changelog

Version Description
5.6.0 Added the $fire_after_hooks parameter.
4.7.0 Added the $wp_error parameter to allow a WP_Error to be returned on failure.
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Example
    Inserts an attachment to a parent with a post ID of 37:

     $wp_upload_dir['url'] . '/' . basename( $filename ), 
    	'post_mime_type' => $filetype['type'],
    	'post_title'     => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
    	'post_content'   => '',
    	'post_status'    => 'inherit'
    );
    
    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
    
    // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    
    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    
    set_post_thumbnail( $parent_post_id, $attach_id );
    ?>

  2. Skip to note 8 content

    If you are trying to make a media attachment, caption and description are ‘post_excerpt’ and ‘post_content’, respectively. Example:

        wp_insert_attachment(
    		array(
    			'guid' => $upload['url'],
    			'post_title' => sanitize_text_field( $title ),
    			'post_excerpt' => sanitize_text_field( $caption ),
    			'post_content' => sanitize_text_field( $description ),
    			'post_mime_type' => $response_headers['content-type'],
     		),
    		$upload['file'],
    		0
    	);