How To Upload Images When Creating Shipments via API
Code goes to your active theme’s functions.php file:
1. Use this custom function:
function save_base64image_to_post_attachment( $base64_img, $title ) { // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once( ABSPATH . 'wp-admin/includes/image.php' ); // Upload dir. $upload_dir = wp_upload_dir(); $upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR; $img = str_replace( 'data:image/jpeg;base64,', '', $base64_img ); $img = str_replace( ' ', '+', $img ); $decoded = base64_decode( $img ); $filename = $title . '.jpeg'; $file_type = 'image/jpeg'; $hashed_filename = md5( $filename . microtime() ) . '_' . $filename; // Save the image in the uploads directory. $upload_file = file_put_contents( $upload_path . $hashed_filename, $decoded ); $attachment = array( 'post_mime_type' => $file_type, 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $hashed_filename ) ), 'post_content' => '', 'post_status' => 'inherit', 'guid' => $upload_dir['url'] . '/' . basename( $hashed_filename ) ); $attach_id = wp_insert_attachment( $attachment, $upload_dir['path'] . '/' . $hashed_filename ); // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata( $attach_id, $upload_dir['path'] . '/' . $hashed_filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); return $attach_id; }
2. This will be the hook that will save the attachment ids to the wpcargo shipment created:
function wpcargo_api_after_add_shipment_save_images_cb($shipmentID, $request) { $custom_field_meta_key = 'custom_shipment_images'; // change this one with your custom field file meta key $pre_shipment_images = $request->get_param( $custom_field_meta_key ); $attachment_ids = array(); if($pre_shipment_images && is_array($pre_shipment_images)) { $counter = 1; foreach($pre_shipment_images as $base64) { $title = 'image-' . $counter . '-' . time(); $att_id = save_base64image_to_post_attachment($base64, $title); if($att_id && $att_id > 0) { if(!in_array($att_id, $attachment_ids)) { $attachment_ids[] = $att_id; } } $counter++; } } if($attachment_ids && is_array($attachment_ids)) { $attachment_ids_imploded = implode(',', $attachment_ids); update_post_meta($shipmentID, $custom_field_meta_key, $attachment_ids_imploded); } } add_action('wpcargo_api_after_add_shipment', 'wpcargo_api_after_add_shipment_save_images_cb', 99, 2);