How to install the thumbnail of a wordpress post from frontend?

to create post from front-end there is a field
<input type="file" name="pictures[]" multiple="multiple">
with the ability to upload several pictures. how to set thumbnail for a post?

in php:
$post_id = wp_insert_post($new_post);
 require_once( ABSPATH . 'wp-admin/includes/image.php' );
 require_once( ABSPATH . 'wp-admin/includes/file.php' );
 require_once( ABSPATH . 'wp-admin/includes/media.php' );
 $meta_name_img = "ad_img";
 $count = 0;

 foreach ($_FILES["pictures"]["error"] as $key => $error) {
 if ($error == UPLOAD_ERR_OK) {
 $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
 $name = basename($_FILES["pictures"]["name"][$key]);
 @copy($tmp_name, ABSPATH.'wp-content/uploads/'.$name);
 $ad_meta_img_new = "ad_img".$count;
 add_post_meta($post_id, $ad_meta_img_new, get_site_url().'/wp-content/uploads/'.$name); 
 $attach_id_img = media_handle_upload('ad_img1', $post_id ); 
 set_post_thumbnail($post_id, $attach_id_img);

Tell me why is not working?

in html output a thumbnail using
<?php the_post_thumbnail(); ?>
June 10th 19 at 16:32
0 answer

Find more questions by tags WordPress