I'm developing a site that is using Wordpress for database interactions, but I'm not really using features like pages or posts or widgets.
I'm trying to create an input form that allows the user to upload an image without having to go to the media library.
The image files do go to the uploads folder, but for some reason their size is 0kb and they don't work. I can't open them in a image viewer program and they don't show up in the media library.
Here is my attempt:
Ajax part:
async function sendImageToWordpress(thePath) {
let responseForPostToDatabase = '';
/* Ajax call here */
let myAjax = await jQuery.ajax({
type: "POST",
url: adminAjaxURL, /* this adminAjaxURL variable has been defined in header.php */
data: ({
action: "add_attachment",
thePath: thePath,
}),
success: function(response){
responseForPostToDatabase = response;
return('success');
},
error: function(){
return('ajax error!!!!');
}
})
return(responseForPostToDatabase);
/* Return statement here */
}
Here is the relevant parts from functions.php:
//SEND IMAGE INTO WORDPRESS
function new_attachment(){
$image_url = ($_POST["thePath"]);
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = basename( $image_url );
if ( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
}
else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents( $file, $image_data );
$wp_filetype = wp_check_filetype( $filename, null );
echo $image_url;
exit();
}
add_action('wp_ajax_add_attachment','new_attachment'); //add an image file
Can you point me in the right direction?