50, ] ); if (wp_remote_retrieve_response_code($response) !== 200) { wu_log_add('screenshot-generator', $log_prefix . wp_remote_retrieve_response_message($response), LogLevel::ERROR); return false; } if (is_wp_error($response)) { wu_log_add('screenshot-generator', $log_prefix . $response->get_error_message(), LogLevel::ERROR); return false; } /* * Check if the results contain a PNG header. */ if (! str_starts_with($response['body'], "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a")) { wu_log_add('screenshot-generator', $log_prefix . __('Result is not a PNG file.', 'wp-ultimo'), LogLevel::ERROR); return false; } $upload = wp_upload_bits('screenshot-' . gmdate('Y-m-d-H-i-s') . '.png', null, $response['body']); if ( ! empty($upload['error'])) { wu_log_add('screenshot-generator', $log_prefix . json_encode($upload['error']), LogLevel::ERROR); return false; } $file_path = $upload['file']; $file_name = basename($file_path); $file_type = wp_check_filetype($file_name, null); $attachment_title = sanitize_file_name(pathinfo($file_name, PATHINFO_FILENAME)); $wp_upload_dir = wp_upload_dir(); $post_info = [ 'guid' => $wp_upload_dir['url'] . '/' . $file_name, 'post_mime_type' => $file_type['type'], 'post_title' => $attachment_title, 'post_content' => '', 'post_status' => 'inherit', ]; // Create the attachment $attach_id = wp_insert_attachment($post_info, $file_path); // Include image.php require_once ABSPATH . 'wp-admin/includes/image.php'; // Define attachment metadata $attach_data = wp_generate_attachment_metadata($attach_id, $file_path); // Assign metadata to attachment wp_update_attachment_metadata($attach_id, $attach_data); wu_log_add('screenshot-generator', $log_prefix . __('Success!', 'wp-ultimo')); return $attach_id; } }