Codex tools: Log in
Contents |
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(). Returns the ID of the entry created in the wp_posts table.
<?php wp_insert_attachment( $attachment, $filename, $parent_post_id ); ?>
Returns the resulting post ID (int) on success - likely returns 0 on failure.
To insert an attachment to a parent with a post ID of 37:
<?php
$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
?>
Using the _wp_relative_upload_path() to build the guid may not be reliable on some servers.
wp_insert_attachment() is located in wp-includes/post.php.
wp_get_attachment_url(), wp_delete_attachment(), wp_insert_post()