daily pastebin goal
51%
SHARE
TWEET

Grab and Insert Image to a post in wordpress

LarcenIII Mar 4th, 2012 109 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. if (isset($IMG_URL) {
  2.         $upload_dir = wp_upload_dir();
  3.         $image_data = file_get_contents($IMG_URL);
  4.         $filename = basename($IMG_URL);
  5.         if(wp_mkdir_p($upload_dir['path']))
  6.                 $file = $upload_dir['path'] . '/' . $filename;
  7.         else
  8.                 $file = $upload_dir['basedir'] . '/' . $filename;
  9.         file_put_contents($file, $image_data);
  10.  
  11.         $wp_filetype = wp_check_filetype($filename, null );
  12.         $attachment = array(
  13.                 'post_mime_type' => $wp_filetype['type'],
  14.                 'post_title' => sanitize_file_name($filename),
  15.                 'post_content' => '',
  16.                 'post_status' => 'inherit'
  17.         );
  18.         $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
  19.         require_once(ABSPATH . 'wp-admin/includes/image.php');
  20.         $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
  21.         wp_update_attachment_metadata( $attach_id, $attach_data );
  22.  
  23.         set_post_thumbnail( $post_id, $attach_id );
  24. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top