You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Steps to add a user customization field inside a WooCommerce product. It allows you to sell a digital or physical product with a custom attribute and retrieve the image in the WC admin order page. CSS not included.
Process :
The user visit a product page
The user setup the product and generate an image through DALLE with the shortcode functionnality
Then press "Download image" which upload the generated image in the WP media library with some metadatas
When uploaded, the script set the WC session and add a custom attributes (custom_image, custom_aig_image_id) to the order
Then the user press "Add to Cart"
Retrieve the data url of the customisation inside cart view and order page view (as custom attribute)
Checkout, add order
In the WC admin dashboard > orders, you will see the product and custom image associated
Maybe add custom attribute "custom image" with value "foo" non visible inside WC edit product page..
Add this code to function.php of your theme / child-theme (prefered) :
add_action('wp_footer', 'custom_aig_javascript_action');
function custom_aig_javascript_action() {
global $post;
if(has_shortcode($post->post_content, 'aig') || is_product()) {
?>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', (event) => {
const form = document.querySelector('.aig-form[data-download="manual"]');
if (form) {
const ajaxurl = form.getAttribute('action');
const observer = new MutationObserver((mutationsList, observer) => {
for(let mutation of mutationsList) {
if (mutation.type === 'childList') {
const buttons = form.querySelectorAll('div.aig-results button.aig-download-button');
buttons.forEach((button, index) => {
// Clone the button to remove all event listeners
let clone = button.cloneNode(true);
button.parentNode.replaceChild(clone, button);
// Add new event listener to the cloned button
clone.addEventListener('click', (event) => {
event.preventDefault();
const figure = clone.closest('figure');
const imgElement = figure.querySelector('img.aig-image');
const imageUrl = imgElement.src;
// Show loading icon
clone.innerHTML = '<span class="dashicons dashicons-ellipsis"></span>';
clone.disabled = true;
fetch(ajaxurl, {
method: "POST",
body: new URLSearchParams({
action: "custom_aig_manual_download",
image_url: imageUrl,
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache",
},
})
.then((response) => response.json())
.then((result) => {
// Remove the button
clone.parentNode.removeChild(clone);
})
.catch((error) => {
console.error("Error API request :", error);
clone.disabled = false;
});
});
});
}
}
});
observer.observe(form.querySelector('div.aig-results'), { childList: true });
}
});
</script>
<?php
}
}
// Add shortcode inside WooCommerce product page
function display_custom_shortcode() {
echo do_shortcode('[aig prompt="Painting of {public_prompt}, including following criterias: {topics}" user_limit="5" user_limit_duration="86400" topics="Impressionism, Surrealism, Portraits, Landscape Painting, Watercolor Techniques, Oil Painting, Street Art, Hyperrealism, Cat, Dog, Bird, Person" download="manual" model="dall-e-2" n="1" user_limit="10"]');
}
add_action('woocommerce_single_product_summary', 'display_custom_shortcode', 10); // priority may change for display
// When aig_manual_download is called, download the image, put in metadata the client IP and possibly the cart/order session ID if present
add_action('wp_ajax_custom_aig_manual_download', 'custom_aig_manual_download');
add_action('wp_ajax_nopriv_custom_aig_manual_download', 'custom_aig_manual_download');
function custom_aig_manual_download() {
if (!wp_doing_ajax()) {
return;
}
$current_user_id = get_current_user_id();
$current_user_ip = $_SERVER['REMOTE_ADDR'];
$meta_value = $current_user_id ? $current_user_id : $current_user_ip;
$image_url = esc_url_raw($_POST['image_url']);
try {
$attachment_id = media_sideload_image($image_url, 0, null, 'id');
if (!$attachment_id) {
throw new Exception(esc_html__('Error downloading the image.', 'custom-artist-image-generator'));
}
add_post_meta($attachment_id, 'downloaded_by', $meta_value);
add_post_meta($attachment_id, 'ip_address', $current_user_ip);
WC()->session->set('aig_custom_image_id', $attachment_id);
wp_send_json(array(
'success' => true,
'message' => esc_html__('Image successfully saved.', 'custom-artist-image-generator'),
'attachment_id' => $attachment_id,
'get_post_meta' => get_post_meta($attachment_id, 'downloaded_by', true),
'ip_address' => get_post_meta($attachment_id, 'ip_address', true),
'wp_session' => [
'session_image_id' => WC()->session->get('aig_custom_image_id'),
'session_id' => WC()->session->get_customer_id(),
]
));
} catch (Exception $e) {
error_log('Exception: ' . $e->getMessage());
wp_send_json_error($e->getMessage());
}
}
// Update a WooCommerce metadata (custom attribute) for each product that has been added to the cart
add_filter('woocommerce_add_cart_item_data', function($cart_item_data, $product_id, $variation_id) {
if ($image_id = WC()->session->get('aig_custom_image_id')) {
$cart_item_data['custom_aig_image_id'] = $image_id;
$image_src = wp_get_attachment_image_src($image_id, 'full');
if ($image_src) {
$cart_item_data['custom_image'] = esc_url($image_src[0]);
}
}
return $cart_item_data;
}, 10, 3);
// In the cart page, add the metadata below the product description in the form of a link redirecting to the Wordpress media file
function display_custom_image_id_in_cart($item_data, $cart_item_data) {
if (isset($cart_item_data['custom_image'])) {
$item_data[] = array(
'key' => __( 'Custom Image URL', 'your-text-domain' ),
'value' => '<a href="' . esc_url($cart_item_data['custom_image']) . '" target="_blank">' . esc_url($cart_item_data['custom_image']) . '</a>',
);
}
return $item_data;
}
add_filter('woocommerce_get_item_data', 'display_custom_image_id_in_cart', 1, 2);
// Add a new header to the order items table
function add_custom_image_header_in_admin_order($order){
echo '<th class="item-custom-image">' . __( 'Custom Image', 'your-text-domain' ) . '</th>';
}
add_action('woocommerce_admin_order_item_headers', 'add_custom_image_header_in_admin_order');
// Add custom metadata to the order item when creating the order
add_action('woocommerce_checkout_create_order_line_item', function($item, $cart_item_key, $values, $order) {
if (isset($values['custom_aig_image_id'])) {
$item->add_meta_data('custom_aig_image_id', $values['custom_aig_image_id']);
$image_src = wp_get_attachment_image_src($values['custom_aig_image_id'], 'full');
if ($image_src) {
$item->add_meta_data('custom_image', esc_url($image_src[0]));
}
}
}, 10, 4);
// Show the custom image under the new header for each item in the order
function display_custom_image_in_admin_order($item_id, $item, $product){
$custom_image = $item->get_meta('custom_image');
if ($custom_image) {
echo '<td class="item-custom-image"><img src="' . esc_url($custom_image) . '" alt=""></td>';
} else {
echo '<td class="item-custom-image"></td>';
}
}
add_action('woocommerce_admin_order_item_values', 'display_custom_image_in_admin_order', 10, 3);
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Steps to add a user customization field inside a WooCommerce product. It allows you to sell a digital or physical product with a custom attribute and retrieve the image in the WC admin order page. CSS not included.
Process :
Maybe add custom attribute "custom image" with value "foo" non visible inside WC edit product page..
Add this code to function.php of your theme / child-theme (prefered) :
Beta Was this translation helpful? Give feedback.
All reactions