I am coding frontend-posting and this includes meta-data of images. I have searched some and wondering about below code,

function my_submission_processor() {
  $post_data = array(
    'post_title' => $_POST['post_title'],
    'post_content' => $_POST['post_content'],
    'post_status' => 'draft'

  $post_id = wp_insert_post( $post_data );

  $upload = wp_upload_bits( $_FILES['image']['name'], null, 
file_get_contents( $_FILES['image']['tmp_name'] ) );

  $wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );

  $wp_upload_dir = wp_upload_dir();

  $attachment = array(
    'guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path( 
             $upload['file'] ),
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )),
    'post_content' => '',
    'post_status' => 'inherit'

  $attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );

  require_once(ABSPATH . 'wp-admin/includes/image.php'); //this is what I wondering

  $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
  wp_update_attachment_metadata( $attach_id, $attach_data );

  update_post_meta( $post_id, '_thumbnail_id', $attach_id );

  wp_redirect( site_url() . '/thank-you/' );



check the below line of code,

require_once(ABSPATH . 'wp-admin/includes/image.php');

I don't know how this works and why image.php is needed here?

The above code is from here. https://premium.wpmudev.org/blog/upload-file-functions/

1 Answer 1


Well you have not mentioned whether your code worked or not because the blog you are following is amazing one. And you should have get the solution from that post.

And regarding your question..

require_once(ABSPATH . 'wp-admin/includes/image.php');

This is a core WordPress file which does all the manipulation on images and its meta data.

Why the code is using this file..

The functionalities you need is not a commonly used functionality. That file is being used by WordPress for all manipulation in backend. But when you want to get image from external source or do some manipulation its better to go in WordPress way.

The functions you see in code like wp_generate_attachment_metadata and wp_update_attachment_metadata fully depends on image.php and without these 2 functions image meta data can not be set properly.

I hope this clears the doubt and help you in someway. :)

  • Great. Please consider to accept and upvote Commented Dec 30, 2017 at 8:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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