i have created a custom plugin which dynamically displays custom fields in woocommerce single product page.
Fields are displayed, added to cart and added to order data and emails.
However i’m trying for days to add a file upload field with no luck.
The field is displayed in the frontend like:
add_action( 'woocommerce_before_add_to_cart_button', 'display_custom_fields' );
function display_custom_fields() {
?>
<p class="form-row validate-required" id="image" >
<span class="woocommerce-input-wrapper">
<label for="image" class=""><?php echo $stamp_welcome_text; ?> </label>
<input type="file" name="image" accept="image/*" >
</span>
</p>
<?php
}
and then added to cart like:
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10,3 );
function add_cart_item_data( $cart_item_data, $product_id ) {
if ($_FILES['image'] ) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_id = media_handle_upload( 'image', 0 );
if ( is_wp_error( $attachment_id ) AND $_FILES['image']['size'] > 0) {
die($attachment_id->get_error_message().'. Παρακαλώ επικοινωνήστε μαζί μας.');
} else $cart_item_data['image'] = $attachment_id;
}
return $item_cart_data;
}
Of course this is only part of the code.The rest of the fields are working perfect. Yes, i have tried the code only by itself if anyone wonders.
I have been "playing" around with it for days and i can’t figure out what’s wrong.
Any help is highly appreciated 🙂
4
Answers
I managed to find a conflict with my template(woodmart) the code works perfectly on twentytwenty and storefront
i should have thought of this earlier and not bang my head in the wall for a week.
You can do this using a plugin such as Product Addons
https://woocommerce.com/products/product-add-ons/
Here’s a link to the documentation that explains specifically about allowing file uploads (they can be free or charge per upload)
https://docs.woocommerce.com/document/product-add-ons/#section-9
Hope this helps!
You could try the following, that will store uploaded image data as custom cart item data and save it as custom order item meta data:
This code goes in functions.php file of your active child theme (or active theme).
Tested in Woocommerce version 4.3.x and working with default WooCommerce products from all types.
For multiple images if someone needs it.