wp_insert_attachment( string|array $args, string|false $file = false, int $parent_post_id, bool $wp_error = false, bool $fire_after_hooks = true ): int|WP_Error
Inserts an attachment.
Contents
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
-
$args
string|array Required -
Arguments for inserting an attachment.
-
$file
string|false Optional -
Filename.
Default:
false
-
$parent_post_id
int Optional -
Parent post ID.
-
$wp_error
bool Optional -
Whether to return a WP_Error on failure.
Default:
false
-
$fire_after_hooks
bool Optional -
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
File: wp-includes/post.php
.
View all references
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
You must log in before being able to contribute a note or feedback.
Example
Inserts an attachment to a parent with a post ID of 37:
If you are trying to make a media attachment, caption and description are ‘post_excerpt’ and ‘post_content’, respectively. Example:
Returns int 0 on failure
If you want to upload a file to the media library from php, you need to use this function:
media_handle_upload()
Once you attach an image to a post, you can make it the featured image for the post by using
set_post_thumbnail()
.Usage