There is a file upload provision in my custom plugin page.

On this, I'm saving the image details into post table as an attachment post type and moving the uploaded file manually. Here is my code:

$wp_upload_dir = wp_upload_dir();
$filetype = $_FILES['img_name'];
$filename = $filetype['name'];
$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'
$attach_id = wp_insert_attachment($attachment, $filename);

Is there any alternative way for move_uploaded_file() in WordPress to get the different dimension of the given image automatically?

  • Try adding wp_generate_attachment_metadata() and wp_update_attachment_metadata() after wp_insert_attachment(). See the first example here for details. Jun 28, 2017 at 19:06
  • $absFilename = $wp_upload_dir['path'].'/'.$filename; $attach_data = wp_generate_attachment_metadata( $attach_id, $absFilename); wp_update_attachment_metadata( $attach_id, $attach_data );
    – Tamilvanan
    Jun 28, 2017 at 19:36
  • 1
    The above code done my job. Thanks again @DaveRomsey.
    – Tamilvanan
    Jun 28, 2017 at 19:37
  • Good, glad to hear! Please add that code as an answer, then stop by in a couple of days and click the checkmark next to it to accept it. This helps keep the site tidy. Thank you! Jun 28, 2017 at 19:40

1 Answer 1


Resized different dimension image sets are generated by using wp_generate_attachment_metadata and wp_update_attachment_metadata method.

$absFilename = $wp_upload_dir['path'].'/'.$filename;
$attach_data = wp_generate_attachment_metadata( $attach_id, $absFilename);
wp_update_attachment_metadata( $attach_id, $attach_data );

This will update the image details in the wp_postmeta table.

Thanks @DaveRomsey

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.