WordPress at a glance

wp_insert_attachment() WP 1.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.

Works based on: wp_insert_post()

No Hooks.

Return

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

Usage

wp_insert_attachment( $args, $file, $parent, $wp_error, $fire_after_hooks );
$args(string|array) (required)
Arguments for inserting an attachment.
$file(string|false)
Filename.
$parent(int)
Parent post ID.
$wp_error(true|false)
Whether to return a WP_Error on failure.
Default: false
$fire_after_hooks(true|false)
Whether to fire the after insert hooks.
Default: true

Notes

  • See: wp_insert_post()

Changelog

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

Code of wp_insert_attachment() WP 5.7.2

<?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 );
}

From tag: wp_insert (insert in DB)

More from category: Attachments (Media files)

No comments
    Log In