Programmatically adding Wordpress post with attachment

0 votes
asked Sep 27, 2010 by salman-khimani

I am getting post_title, post_content and other things in $_REQUEST as well as an image file. I want to save all that as a post in the wordpress database. I have on my page

$user_ID; //getting it from my function
$post_title = $_REQUEST['post_title'];
$post_content = $_REQUEST['post_content'];
$post_cat_id = $_REQUEST['post_cat_id']; //category ID of the post
$filename = $_FILES['image']['name'];

//I got this all in a array

$postarr = array(
 'post_status' => 'publish',
 'post_type' => 'post',
 'post_title' => $post_title,
 'post_content' => $post_content,
 'post_author' => $user_ID,
 'post_category' => array($category) 
$post_id = wp_insert_post($postarr);


This will get all the things in database as post but I don't know how to add the attachment and its post meta.

How can I do that? Can anybody help me? I am really confused and have spent a few days trying to solve this.

2 Answers

0 votes
answered Sep 27, 2010 by todd-moses

To add an attachment, use wp_insert_attachment():


  $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():

<?php wp_update_attachment_metadata( $post_id, $data ) ?> 
0 votes
answered Sep 25, 2014 by j-d

If you need to upload the attachment as well as inserting it into the database, you should use media_handle_upload(), which will do all of that for you. All you have to do is give it the index of the file in the $_FILES array and the ID of the parent post:

$attachment_id = media_handle_upload( 'image', $post_id );

if ( is_wp_error( $attachment_id ) ) {
      // The upload failed.
} else {
      // The upload succeeded!
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter