wp_insert_attachment

Insert an attachment.

Description

(int|WP_Error) wp_insert_attachment( (string|array) $args, (constant) $file = false, (int) $parent = 0, (bool) $wp_error = false ); 

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.

Returns (int|WP_Error)

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

Parameters (4)

0. $args (string|array)
Arguments for inserting an attachment.
1. $file — Optional. (constant) => false
Filename.
2. $parent — Optional. (int)
Parent post ID.
3. $wp_error — Optional. (bool) => false
Whether to return a WP_Error on failure. Default false.

Usage

  1. if ( !function_exists( 'wp_insert_attachment' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Arguments for inserting an attachment. 
  5. $args = null; 
  6.  
  7. // Optional. Filename. 
  8. $file = false; 
  9.  
  10. // Optional. Parent post ID. 
  11. $parent = -1; 
  12.  
  13. // Optional. Whether to return a WP_Error on failure. Default false. 
  14. $wp_error = false; 
  15.  
  16. // NOTICE! Understand what this does before running. 
  17. $result = wp_insert_attachment($args, $file, $parent, $wp_error); 
  18.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/post.php  
  1. function wp_insert_attachment( $args, $file = false, $parent = 0, $wp_error = false ) { 
  2. $defaults = array( 
  3. 'file' => $file,  
  4. 'post_parent' => 0 
  5. ); 
  6.  
  7. $data = wp_parse_args( $args, $defaults ); 
  8.  
  9. if ( ! empty( $parent ) ) { 
  10. $data['post_parent'] = $parent; 
  11.  
  12. $data['post_type'] = 'attachment'; 
  13.  
  14. return wp_insert_post( $data, $wp_error );