wp_insert_attachment() WordPress Function

The wp_insert_attachment() function is used to insert an attachment into the WordPress database. The function can be used to insert an attachment into a post or page, or it can be used to insert an attachment into the media library.

wp_insert_attachment( string|array $args, string|false $file = false, int $parent, bool $wp_error = false, bool $fire_after_hooks = true ) #

Insert 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.

Top ↑

See also


Top ↑

Parameters

$args

(string|array)(Required)Arguments for inserting an attachment.

$file

(string|false)(Optional) Filename.

Default value: false

$parent

(int)(Optional) Parent post ID.

$wp_error

(bool)(Optional) Whether to return a WP_Error on failure.

Default value: false

$fire_after_hooks

(bool)(Optional) Whether to fire the after insert hooks.

Default value: true


Top ↑

Return

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


Top ↑

Source

File: wp-includes/post.php

function wp_insert_attachment( $args, $file = false, $parent = 0, $wp_error = false, $fire_after_hooks = true ) {
	$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_error, $fire_after_hooks );
}


Top ↑

Changelog

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

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More