I am trying to fetch and insert images outside the wordpress environment to a custom post via PHP.
How to move/upload that image to wordpress upload directory year date folder format just like wordpress do and set that image to featured image against the custom post?
Also to upload image to custom post gallery?
Below is my code
$filename = $image['name'];
$target_path = "../wp-content/uploads/";
$target_path = $target_path . $filename;
$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['baseurl'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $attachment, $target_path, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
i have managed to upload the image to my uploads directory but cannot unable to create the year and date folder . this there any wp function for it ??