Advertisement
olie480

WP: Insert File into Wordpress Media Library PHP

Dec 21st, 2013
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.14 KB | None | 0 0
  1. http://cube3x.com/2013/03/upload-files-to-wordpress-media-library-using-php/
  2.  
  3. <form action="upload_file.php" method="post" enctype="multipart/form-data">
  4.     <label for="file">Filename:</label>
  5.     <input type="file" name="myfile" id="myfile">
  6.     <input type="submit" name="submit" value="Submit">
  7. </form>
  8.  
  9. <?php
  10. if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
  11. $uploadedfile = $_FILES['myfile'];
  12. $upload_overrides = array( 'test_form' => false );
  13. $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
  14. if ( $movefile ) {
  15.     //file is uploaded successfully. do next steps here.
  16. }
  17.  
  18. if ( $movefile ) {
  19.     $wp_filetype = $movefile['type'];
  20.     $filename = $movefile['file'];
  21.     $wp_upload_dir = wp_upload_dir();
  22.     $attachment = array(
  23.         'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
  24.         'post_mime_type' => $wp_filetype,
  25.         'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
  26.         'post_content' => '',
  27.         'post_status' => 'inherit'
  28.     );
  29.     $attach_id = wp_insert_attachment( $attachment, $filename);
  30. }
  31.  
  32. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement