Добавить изображение в сообщении

Я попытался прикрепить изображение к сообщению, но мой код не работает, и я пробовал много вещей, много кода и т. Д. Что случилось? Я пробовал с этим:

$postData = array( 'post_title' => 'My post', 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array( 8,39 ) ); $post_id = wp_insert_post( $postData ); $getImageFile = '/var/www/html/wp-content/uploads/pluginQ/test.jpg'; $upload_dir = wp_upload_dir(); $image_data = file_get_contents($getImageFile); $filename = basename($getImageFile); if(wp_mkdir_p($upload_dir['path'])){ $file = $upload_dir['path'] . '/' . $filename; } else{ $file = $upload_dir['basedir'] . '/' . $filename; } file_put_contents($file, $image_data); $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $file, $post_id ); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $post_id, $attach_id ); 

Solutions Collecting From Web of "Добавить изображение в сообщении"

Эй, у меня была такая же проблема около 4 5 дней, пока я не нашел этот код, попробую некоторые настройки и посмотрю, работает ли 🙂

 #Upload and Create attachment if (!function_exists('wp_generate_attachment_metadata')){ require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); } $upload = wp_upload_bits( $_FILES['file']['name'], null, file_get_contents( $_FILES['file']['tmp_name'] ) ); $wp_filetype = wp_check_filetype( basename( $upload['file'] ), null ); $check = getimagesize($_FILES["file"]["tmp_name"]); if($check !== false) { $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; wp_trash_post( $post_id ); } $wp_upload_dir = wp_upload_dir(); $attachment = array( 'guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $upload['file'] ), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )), 'post_content' => '', 'post_author' => $user_id, 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id ); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] ); wp_update_attachment_metadata( $attach_id, $attach_data ); #Upload and Create attachment #Use attachment update_post_meta( $post_id, '_thumbnail_id', $attach_id ); #Use attachment