This function inserts an attachment into the media library. The function should be used in conjunction with wp_update_attachment_metadata() and wp_generate_attachment_metadata(). It returns the ID of the entry created in the wp_posts table.
This function is part of the low-level API used by WordPress for handling attachments. To perform the entire attachment upload and insertion process at once, you will want to use media_handle_upload() instead in most cases.
<?php wp_insert_attachment( $attachment, $filename, $parent_post_id ); ?>
Returns the resulting post ID (int) on success or 0 (int) on failure.
To insert an attachment to a parent with a post ID of 37:
<?php // $filename should be the path to a file in the upload directory. $filename = '/path/to/uploads/2013/03/filename.jpg'; // The ID of the post this attachment is for. $parent_post_id = 37; // Check the type of file. We'll use this as the 'post_mime_type'. $filetype = wp_check_filetype( basename( $filename ), null ); // Get the path to the upload directory. $wp_upload_dir = wp_upload_dir(); // Prepare an array of post data for the attachment. $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' ); // 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 );
_wp_relative_upload_path() to build the guid may not be reliable on some servers.
wp_insert_attachment() is located in