Programmatically adding WordPress post with attachment. To add an attachment, use wp_insert_attachment() built-in function:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( '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 ); |
To add Meta Data, use wp_update_attachment_metadata():
1 2 3 | <?php wp_update_attachment_metadata( $post_id, $data ); ?> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.