1

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);
move_uploaded_file($_FILES['test_upload_pdf']['tmp_name'],$wp_upload_dir['path'].'/'.$_FILES['test_upload_pdf']['name']);

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

| improve this question | | | | |
  • Try adding wp_generate_attachment_metadata() and wp_update_attachment_metadata() after wp_insert_attachment(). See the first example here for details. – Dave Romsey Jun 28 '17 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 '17 at 19:36
  • 1
    The above code done my job. Thanks again @DaveRomsey. – Tamilvanan Jun 28 '17 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! – Dave Romsey Jun 28 '17 at 19:40
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

| improve this answer | | | | |

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.