I have been working with a front end upload and post creation script. For some reason calling the media_handle_upload function from my project-save.php file is returning as an undefined function. Is there something I a missing? Permissions, additional files, coffee?

Here is my function in functions.php

function process_attachments() {
    //Process Uploads   
      if (!function_exists('wp_generate_attachment_metadata')){
          require_once(ABSPATH . "wp-admin" . '/includes/image.php');
          require_once(ABSPATH . "wp-admin" . '/includes/file.php');
          require_once(ABSPATH . "wp-admin" . '/includes/media.php');
       if ($_FILES) {
          foreach ($_FILES as $file => $array) {
              if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                  return "upload error : " . $_FILES[$file]['error'];
              $attach_id = media_handle_upload( $file, $post_id );

      //Attachment ID if set
      if ($attach_id > 0){
          //and if you want to set that image as Post  then use:
          return $attach_id;

And I call this from my project-save.php file like so (this is slimmed down, I didnt feel the need to show the post creation form data)

$attach_id = process_attachments();
      if($attach_id > 0) {
          //and if you want to set that image as Post  then use:
          $whimkey->attach_id = $attach_id;

Since media_handle_upload is a Wordpress function how could it be undefined?


So I dont know if its the best way but my problem was the if statement surrounding the require_once on the necessary files that contain the function. Commented out the IF statement and it did the trick. I'll go have that coffee now ;)

//if (!function_exists('wp_generate_attachment_metadata')){
          require_once(ABSPATH . 'wp-admin/includes/image.php');
          require_once(ABSPATH . 'wp-admin/includes/file.php');
          require_once(ABSPATH . 'wp-admin/includes/media.php');

Based on your code, you have put the wrong condition within if statement. You can check the first example here: Media handle upload

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.