I have an upload script that allows users to save an image created in a canvas element to an images directory on my site, and I'm trying to have Media Library recognize the uploaded image so that users can add the image to their posts. The php and html code that builds the canvas element and saves the file are not integrated at all with Wordpress, though if there is a way to do this, I'm open to it. I'm wondering if there's a bit of code I can add to my upload.php file following the function that saves the image to the server that will force the Media Library to recognize it. Code in the current upload.php file is below. Thanks!
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the dataURL
$dataURL = $_POST["image"];
// the dataURL has a prefix (mimetype+datatype)
// that we don't want, so strip that prefix off
$parts = explode(',', $dataURL);
$data = $parts[1];
// Decode base64 data, resulting in an image
$data = base64_decode($data);
// set value for upload directory
define('UPLOAD_DIR', 'images/');
// create a temporary unique file name
$file = uniqid() . '.png';
$file_path = UPLOAD_DIR . $file;
// write the file to the upload directory
$success = file_put_contents($file_path, $data);
}
timDesain Nanang answers:
You can try this code:
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the dataURL
$dataURL = $_POST["image"];
// the dataURL has a prefix (mimetype+datatype)
// that we don't want, so strip that prefix off
$parts = explode(',', $dataURL);
$data = $parts[1];
// Decode base64 data, resulting in an image
$data = base64_decode($data);
// set value for upload directory
define('UPLOAD_DIR', 'images/');
// create a temporary unique file name
$file = uniqid() . '.png';
$file_path = UPLOAD_DIR . $file;
// write the file to the upload directory
$success = file_put_contents($file_path, $data);
if($success) {
// $filename should be the path to a file in the upload directory.
$filename = $file_path;
// The ID of the post this attachment is for.
$parent_post_id = 0;
// Check the type of tile. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}//success
}//upload
PS. <em>$file_path</em> as <em>$filename</em>
codex: [[LINK href="http://codex.wordpress.org/Function_Reference/wp_insert_attachment"]]http://codex.wordpress.org/Function_Reference/wp_insert_attachment[[/LINK]]
jdozierezell comments:
This looks pretty good, but I'm getting a 500 error every time I try to run any wordpress function. The upload file is outside of wordpress and is accessed through an iframe within a custom post type. Is there a way I can include the necessary files from outside the wordpress admin? For instance, rather than using ABSPATH, I can replace with $_SERVER['DOCUMENT_ROOT'] to include the required files, but then other files (/wp-includes/functions.php) use ABSPATH within them and are causing errors that I can't fix without hacking them. Any ideas?
timDesain Nanang comments:
try to add:
require_once( 'path/to/wp-blog-header.php' );
before the code.
It will recognize all wordpress functions and constant.
jdozierezell comments:
Thanks! That worked. One thing to note was that when using this method I wasn't able to attach any images outside of the uploads folder. Not sure if that's unique to this method or generally the way the media library works. Not a problem though. Just changed
define('UPLOAD_DIR', 'images/');
to
$quilt_time = new DateTime;
define('UPLOAD_DIR', $quilt_time->format('Y') . '/' . $quilt_time->format('m') . '/');
and that did the trick.
I'm new to WP Questions and not sure how to award the money, but you definitely get my vote. Seems like it's a community award thing, but if there's something else I need to do, just let me know.
Kyle answers:
The two functions you want to focus on are wp_insert_attachment (attachments is the 'post type' WP uses for media items in the DB) and wp_update_attachment_metadata (data for your attachment). With your $file object you will want to add the attachment with something like this:
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = $name;
$content = '';
$attachment = array(
'post_mime_type' => $type,
'guid' => $dataURL,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => $content,
);
$id = wp_insert_attachment($attachment, $file, $post_id);
You only need $post_id if you are attaching it to a certain post/user, etc.
From there, check for any errors and update the meta:
if ( !is_wp_error($id) ) {
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
}
Arnav Joy answers:
Please see this link
http://www.hughlashbrooke.com/wordpress-upload-user-submitted-files-frontend/
Bob answers:
May be these become helpful to you.
http://wordpress.stackexchange.com/questions/60802/how-to-register-images-uploaded-via-ftp-in-media-library
http://wordpress.stackexchange.com/questions/12866/how-to-get-an-image-transferred-via-ftp-or-script-to-appear-in-media-manager