I’m using the following code to upload the logo as a featured image for post and works without any problem
Yes, the WordPress part in that code and the other code is good.
However, if your first code is placed above/before your second code, then the problem is the following if, which applies to both the file upload inputs in your form (post_image and trabajos_empresa):
if($_FILES[$file]['error'] !== UPLOAD_ERR_OK){
return "upload error : " . $_FILES[$file]['error'];
}
Because for the trabajos_empresa input, which is an array (because it has the multiple attribute), $_FILES['trabajos_empresa']['error'] is actually an array (of upload status, which are integers), hence $_FILES['trabajos_empresa']['error'] !== UPLOAD_ERR_OK (i.e. <array> !== <integer>) is true and therefore the return line in the above code skips uploading the files uploaded via the trabajos_empresa input.
And your second code is actually good, so try changing the first code (the whole if($_FILES) { ... } if($attach_id > 0) { ... } part) to this one:
if ( isset( $_FILES['post_image'] ) ) {
$attach_id = media_handle_upload( 'post_image', $post_id );
if ( $attach_id && ! is_wp_error( $attach_id ) ) {
set_post_thumbnail( $post_id, $attach_id );
}
}
Notes:
-
I used
set_post_thumbnail()to set the post thumbnail. -
I didn’t check for the
UPLOAD_ERR_OKbecause it will be done viamedia_handle_upload().
And despite your second code is good, you should check if $_FILES['trabajos_empresa'] is set like I did above with the other input. So for example, if ( isset( $_FILES['trabajos_empresa'] ) ) { put your second code here }. Also, if an upload didn’t succeed, you could actually inspect the error message like so: echo $attachment_id->get_error_message();.