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 = trailingslashit( $upload_dir['path'] );
// Decode base64 string.
$img = str_replace( 'data:image/jpeg;base64,', '', $base64_img );
$img = str_replace( ' ', '+', $img );
$decoded = base64_decode( $img );
// Create filename.
$filename = $title . '.jpeg';
$file_type = 'image/jpeg';
$hashed_filename = md5( $filename . microtime() ) . '_' . $filename;
// Save the image in the uploads directory.
$saved = file_put_contents( $upload_path . $hashed_filename, $decoded );
if ( ! $saved ) {
return false;
}
// Prepare attachment post data.
$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 ),
);
// Insert attachment into media library.
$attach_id = wp_insert_attachment( $attachment, $upload_path . $hashed_filename );
// Generate metadata and update.
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload_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 to your actual field 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 && ! in_array( $att_id, $attachment_ids ) ) {
$attachment_ids[] = $att_id;
}
$counter++;
}
}
if ( ! empty( $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 );


