Created
August 11, 2013 12:21
-
-
Save sang4lv/6204647 to your computer and use it in GitHub Desktop.
Insert file to media library and attach it to post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function attachMediaFromUrl( $url, $post_id = 0, $file_type = null ) { | |
| //Fetch Media And Set Path | |
| require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
| $upload_dir = wp_upload_dir(); | |
| $file_name = basename( $url ); | |
| $image_data = @file_get_contents( $url ); | |
| $file = wp_mkdir_p( $upload_dir['path'] ) ? $upload_dir['path'] : $upload_dir['basedir']; | |
| $file .= '/' . $file_name; | |
| //Insert Media | |
| @file_put_contents( $file, $image_data ); | |
| //Check For File Type | |
| $wp_filetype = wp_check_filetype( $file_name, $file_type ); | |
| $attachment = array( | |
| 'post_title' => sanitize_file_name( $file_name ), | |
| 'post_status' => 'inherit' | |
| 'post_content' => '', | |
| 'post_mime_type' => $wp_filetype['type'], | |
| ); | |
| //Perform Insert and Update Meta Info | |
| $attach_id = wp_insert_attachment( $attachment, $file, $post_id ); | |
| $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); | |
| wp_update_attachment_metadata( $attach_id, $attach_data ); | |
| return $attach_id; | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment