2

I defined image dimensions in media (WP) and in functions.php addedd some 2 custom dimensions for image upload. When I upload images through WP admin everything is ok.

But now I have client which is uploadin 100 images via FTP to some folder on his site and I was wondering if there is a way to add this image to post programmatically?

Every image has name like post_ID.jpg (for exam. 450.jpg) and this is how I will know which image to add to which post but my question is how to add programmatically with wp functions (resize/crop (like it does when i add via WP admin)).

This images are in custom folder: /product_images/

Thank's for help

1 Answer 1

4

Solved..

here is a solution:

$post_id = 809; // example post_ID
$filename= '/my_images/809.jpg';
$description = 'some description';

# remove all attachments
$wpdb->query("UPDATE post_parent ='0' WHERE post_type='attachment' AND post_parent='".$post_id."'");

# upload / resize / crop image (to WP images folder)
media_sideload_image($filename,$post_id,$description);

$last_attachment = $wpdb->get_row($query = "SELECT * FROM {$wpdb->prefix}posts ORDER BY ID DESC LIMIT 1", ARRAY_A);
$attachment_id = $last_attachment['ID'];

# set featured image
add_post_meta($post_id, '_thumbnail_id', $attachment_id);
Sign up to request clarification or add additional context in comments.

3 Comments

just a notice - i used this manyy times - under some scenarios the _thumbnail ID will not be the last to be uploaded .. just a heads up .
@ObmerkKronen - in sthi script it will be.
you can get rid of two lines by doing this: $attachment_id = media_sideload_image($filename, $post_id, $description, 'id');

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.