WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am scrapping contents from my others sites into my wordpress site, i did all and below is my insert query

$my_post = array(
   'post_title'    => $my_title,
   'post_status'   => 'publish',
   'post_author'   => 1,
   'post_category' => array(5),
   'post_content'  => $res_final,
   'post_date'     => date('Y-m-d H:i:s'),
   'post_date_gmt' => date('Y-m-d H:i:s'),
   'post_type'     => 'post'

 $post_id = wp_insert_post( $my_post );

I can able to insert my titles and contents and yes it is displaying :), even i can see images inserting into the post as image comes along with the content, but i have planned to take the image alone from the content and stored separately as a post image so that it will come in the front page.

Any help on how to add the image into the post, and what is the best way to insert my image URL, an insert query to do this. Please help me

share|improve this question

Read about wp_insert_attachment(), wp_update_attachment_metadata() and wp_generate_attachment_metadata()

To add an attachment, use wp_insert_attachment() example:

  $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 );
share|improve this answer
Dear Pontus, you showed me the correct way. I used the below code and now i am getting the featured image, but when i edit the featured image for post id 22 – user2560169 Jul 31 '13 at 11:46
the code is used was wordpress.stackexchange.com/questions/40301/… – user2560169 Jul 31 '13 at 11:49

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.