Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hlashbrooke
Created March 20, 2014 06:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hlashbrooke/9658199 to your computer and use it in GitHub Desktop.
Save hlashbrooke/9658199 to your computer and use it in GitHub Desktop.
WordPress: Upload user-submitted files from the frontend
<?php
function upload_user_file( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
?>
<?php
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = upload_user_file( $file );
}
}
}
?>
@duyphuongn
Copy link

Hello. I come across your Gist while searching for a solution to upload media from the front-end. Everything works well, but there's problem: When you delete the media, the physical files won't be deleted from disk, only the post is removed from database.

After searching, I found the problem coming from line 22. In wp_insert_attachment, the 2nd arguments should be absolute path on server, not the URI. You're passing the URI with $file_return['url']. It should be changed to

$attachment_id = wp_insert_attachment( $attachment, $file_return['file'] );

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment