Use the following code.
<?php
// Upload image to wordpress media and save image url to custom field.
if(isset($_FILES['images'])) {
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $_FILES['images'], array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
echo $file_return['error'];
} else {
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_return['file'] ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url'],
'post_parent' => $post_id,
);
// Insert attachment
$attachment_id = wp_insert_attachment( $attachment, date('Y/m/') . basename($file_return['url']) );
// Set post thumbnail
if( !has_post_thumbnail($post_id) ) {
set_post_thumbnail($post_id, $attachment_id);
}
// Update post meta
if( $attachment_id ) {
$file_location = get_bloginfo('url') . '/app/uploads/' . date('Y/m/') . basename($file_return['url']);
update_post_meta($attachment_id, '_wp_attachment_metadata', serialize(array($file_location)));
}
}
}