Skip to content

Instantly share code, notes, and snippets.

@seb86
Last active September 28, 2024 21:06
Show Gist options
  • Save seb86/799e33ebaf82310bf0499a555728dc28 to your computer and use it in GitHub Desktop.
Save seb86/799e33ebaf82310bf0499a555728dc28 to your computer and use it in GitHub Desktop.
CoCart: Upload image URLs with item to cart.
<?php
/**
* An example on adding support for uploading images with products to the cart.
*/
add_filter( 'cocart_after_item_added_to_cart', 'upload_image_urls_with_item', 10, 2 );
/**
* For any image URL set while adding to the cart, upload and store location of uploaded image.
*
* @param array $item_added_to_cart The product added to cart.
* @param WP_REST_Request $request The request object.
*/
function upload_image_urls_with_item( $item_added_to_cart, $request ) {
$upload_images = ! empty( $request['upload_images'] ) ? $request['upload_images'] : array();
$item_key = $item_added_to_cart['key'];
$uploaded_images = array();
foreach ( $upload_images as $key => $url ) {
$uploaded_image = cocart_upload_image_from_url( esc_url_raw( $url ) );
if ( is_wp_error( $uploaded_image ) ) {
throw new CoCart_Data_Exception( 'cocart_uploaded_image_error', $uploaded_image->get_error_message(), 400, array( 'source' => $url ) );
}
$uploaded_images[$item_key][basename($uploaded_image['file'])] = $uploaded_image['url'];
}
// Store the uploaded images in session under the item key.
WC()->session->set( 'cocart_uploaded_images', $uploaded_images );
}
add_filter( 'cocart_cart_items', 'return_uploaded_images', 10, 2 );
/**
* Returns the uploaded images for each item in the cart (if any).
*
* @param array $cart_contents Cart contents before modifications.
* @param int $item_key Unique identifier for item in cart.
*
* @return array $cart_contents Cart contents after modifications.
*/
function return_uploaded_images( $cart_contents, $item_key ) {
$uploaded_images = WC()->session->get( 'cocart_uploaded_images' );
if ( empty( $uploaded_images ) ) {
return $cart_contents;
}
if ( array_key_exists( $item_key, $uploaded_images ) ) {
$cart_contents[$item_key]['uploaded_images'] = $uploaded_images[$item_key];
}
return $cart_contents;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment