0

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

1

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

To add an attachment, use wp_insert_attachment() example:

<?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 );
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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