Advertisement
LarcenIII

Grab and Insert Image to a post in wordpress

Mar 4th, 2012
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.84 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement