Insert post in database works correct.Uploading file in wordpress uploads folder works correct also.The problem is I can't set this file in admin set featured image section. I need to upload this file with my function crb_insert_email_as_post. I don't know when I'm wrong. Can someone help? This is my function for updating wordpress database
function crb_insert_email_as_post( $email ) {
$post_attr = [
'post_type' => 'crb_form_submission',
'post_title' => $email->crb_get_subject(),
'post_content' => $email->crb_get_message(),
'post_status' => 'publish',
];
$post_id = wp_insert_post( $post_attr );
add_post_meta( $post_id, '_crb_sender', $email->crb_get_sender() );
add_post_meta( $post_id, '_crb_sender_email', $email->crb_get_sender_email()
);
$attachment = array(
'post_mime_type' => $email->crb_get_file_type(),
'post_parent' => $post_id,
'post_title' => '',
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $email-
>crb_get_file_path(), $post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $email-
>crb_get_file_path() );
wp_update_attachment_metadata( $attachment_id , $attach_data );
}
And this is my Email class
class Email {
private $sender;
private $subject;
private $sender_email;
private $message;
private $file;
public function __construct( $sender, $subject, $sender_email, $message, $file = '' ) {
$this->sender = $sender;
$this->subject = $subject;
$this->sender_email = $sender_email;
$this->message = $message;
$this->file = $file;
}
public function crb_get_sender() {
return $this->sender;
}
public function crb_get_subject() {
return $this->subject;
}
public function crb_get_sender_email() {
return $this->sender_email;
}
public function crb_get_message() {
return $this->message;
}
public function crb_get_file() {
return $this->file;
}
public function crb_get_file_type() {
return $this->file['file']['type'];
}
function crb_get_file_path() {
return wp_upload_dir()['path'] . '/' . $this->file['file']['name'];
}
public function crb_move_file_in_uploads() {
if ( ! $this->file ) {
return;
}
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$movefile = wp_handle_upload( $this->file['file'], 'wp_handle_upload' );
$uploadedfile = $this->file['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
}
}