I need to insert post programatically in wordpress.. I finished to insert title and content.. But image is not uploaded and attached.. Can you suggest me..

$post_id = wp_insert_post(
        'post_author'   => $user->ID,
            'post_title'    => $Title,
            'post_content'   =>$Content,
            'post_status'   => 'publish',
            'post_type'   => 'post',
            'guid'      =>      $site_url . '/?p=' . $post_id

$Featured_image = http://ecx.images-amazon.com/images/I/51l-rEon-NL._SL110_.jpg;
$year = date("Y");   
$month = date("m"); 
$url = '/wp-content/uploads/'. $year . '/' . $month . '/'  . basename($Featured_image);

// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $Featured_image ), null );

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
'guid'           => $wp_upload_dir['url'] . '/' . basename( $Featured_image ), 
'post_mime_type' => $filetype['type'],
'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $Featured_image )),
'post_content'   => '',
'post_status'    => 'inherit',
'post_type' => 'attachment'

// Insert the attachment.

$attach_id = wp_insert_attachment( $attachment,  $year . '/' . $month . '/'  . basename($Featured_image) ,  $post_id );

require_once( ABSPATH . 'wp-admin/includes/image.php' );

$attach_data = wp_generate_attachment_metadata( $attach_id, $url );

wp_update_attachment_metadata( $attach_id, $attach_data );

set_post_thumbnail( $post_id, $attach_id );

I tried this, but image is displaying in media like this,

enter image description here

At the same time, Image is not storing in uploads folder.. I dont know how to fix this issue.. Can anyone suggest me..


There is a function called media_sideload_image($file, $post_id, $desc, $return); to download an image from the specified URL and attach it to a post. You can use it.

It asked following Parameters.

  • $file : (string) (Required) The URL of the image to download.
  • $post_id : (int) (Required) The post ID the media is to be associated with.
  • $desc : (string) (Optional) Description of the image. Default value: null
  • $return : (string) (Optional) Accepts 'html' (image tag html) or 'src' (URL). Default value: 'html'

It return populated HTML img tag on success, WP_Error object otherwise.


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.