0

I have a product designer plugin to Print t-shirts and mugs. The plugin makes the Design in base64 but doesn't save the uploaded images to the media library. So I came up with a custom Ajax function for the plugin to upload the files to the media library.

The problem is files are uploaded to the media library but I am not able to attach the uploaded file's ID to the cart items and then to the order. The files can be multiple and in the cart, the product can be redesigned which means more files can be uploaded again.

Here is the JQuery and PHP code I managed to make, the meta values are returning empty:

jQuery:

var filesToUpload = [];
jQuery(document).on('change', '#pdr-image-file', function(e){
     var file = $(this)[0].files[0];
     filesToUpload.push(file);
     console.log(filesToUpload);
});    
jQuery(document).on('click', '.pdr-cart-button', function(e){
    e.preventDefault();
    var globaldev_form = new FormData();
    filesToUpload.forEach(function(file, index) {
        globaldev_form.append('file_' + index, file);
    });
    globaldev_form.append('action', 'globaldev_upload_file_data');
    
    jQuery.ajax({
        type: 'POST',
        url: pdr_frontend.ajaxurl,
        data: globaldev_form,
        contentType: false,
        processData: false,
        success: function( response ){
            console.log(response);
            if( response ){
                jQuery(".alertable").attr("style", "display: none !important");
                jQuery.ajax({
                    type: 'POST',
                    url: pdr_frontend.ajaxurl,
                    data: {
                        action: 'globaldev_add_to_cart',
                        id: response.id
                    },
                    success: function( response2 ){
                        console.log(response2);
                        if( response2 != '' && response2 ){
                            jQuery(".alertable").attr("style", "display: block !important");
                        }else{
                            
                        }
                    }
                });
                
            }else{
                
            }
        }
    });
    
});

PHP:

add_action('wp_ajax_globaldev_upload_file_data', 'globaldev_upload_file_data');
add_action('wp_ajax_nopriv_globaldev_upload_file_data', 'globaldev_upload_file_data');
function globaldev_upload_file_data(){
        
    $uploaded_files = $_FILES;
    $upload_overrides = array('test_form' => false);

    $attachment_ids = array();

    foreach ($uploaded_files as $file) {
        $movefile = wp_handle_upload($file, $upload_overrides);

        if ($movefile && !isset($movefile['error'])) {
            // File successfully uploaded, add it to the media library
            $file_path = $movefile['file'];
            $file_url = $movefile['url'];
            
            $attachment = array(
                'guid' => $file_url,
                'post_mime_type' => $movefile['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '', basename($file_path)),
                'post_content' => '',
                'post_status' => 'inherit'
            );

            $attach_id = wp_insert_attachment($attachment, $file_path);

            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
            wp_update_attachment_metadata($attach_id, $attach_data);

            // Store the attachment IDs in an array
            $attachment_ids[] = $attach_id;
        } else {
            // Error handling for file upload
            echo 'Error uploading files.';
            wp_die();
        }
    }

    // Return the attachment IDs as a JSON response
    $cxc_messages = array( 'id' => $attachment_ids );
    wp_send_json( $cxc_messages );
    wp_die();

}

add_action('wp_ajax_globaldev_add_to_cart', 'globaldev_add_to_cart');
add_action('wp_ajax_nopriv_globaldev_add_to_cart', 'globaldev_add_to_cart');
function globaldev_add_to_cart(){
    
    global $woocommerce;
    $attach_id = $_POST['id'];
    $meta_key = sanitize_text_field('uploaded_image');
    $meta_value = sanitize_text_field($attach_id);        
    $cart = WC()->cart->get_cart();
    // Check if the cart is not empty
    if (!empty($cart) && $attach_id != '') {
        
        $imagecount = count($attach_id);
        $woocommerce->cart->cart_contents[$cart_item_key]['image_count'] = $imagecount;
        
        $curr_image_count = $woocommerce->cart->cart_contents[$cart_item_key]['image_count'];
        if($curr_image_count){
            $i = intval($imagecount) + intval($curr_image_count);
        } else {
            $i = 1;
        }
        foreach($attach_id as $single_image){
            $woocommerce->cart->cart_contents[$cart_item_key]['uploaded_image'.$i] = $single_image;
            $woocommerce->cart->set_session();
            $i++;
        }
        
        $cxc_messages = array( 'cart' => $cart, 'key' => $last_item_key, 'item' => $last_item, 'product' => $product_id, 'variation' => $variation_id,  'att_id' => $attach_id, 'imgcount' => $imagecount, 'current_count' => $i);
        
        wp_send_json( $cxc_messages );
    }
    wp_die();
}
/**
 * Display custom input before add to cart button
 */
add_action( 'woocommerce_before_add_to_cart_button', 'mish_before_add_to_cart_btn' );
function mish_before_add_to_cart_btn(){
    $turn_on_this_option = get_field('turn_on_this_option');
    if($turn_on_this_option[0] == 'yes'){
        
        echo '<ul class="product-options">';
        if( have_rows('gd_extra_options') ):
            while( have_rows('gd_extra_options') ) : the_row();
                //print_r(the_row());
                $text_label = get_sub_field('text_label');
                echo '<li><label>'.$text_label.'</label><input type="text" name="'.strtolower(str_replace(' ', '_', $text_label)).'" value="" /></li>';
            endwhile;
        else :
        endif;
        echo '</ul>
        <style>
        .product-options{
            padding:0;
            margin:0;
            list-style: none;
        }    
        </style>';
    }
}
// Display custom metadata in the cart
add_filter('woocommerce_cart_item_name', 'display_cart_item_meta', 10, 3);
function display_cart_item_meta($item_name, $cart_item, $cart_item_key) {
    // Get the custom metadata for the cart item
    $custom_meta = $cart_item['data']->get_meta('image_count');
    // Display the custom metadata if available
    if ($custom_meta) {
                
        //$item_name .= '<br><span class="custom-meta">' . __('Custom Meta:', 'your-text-domain') . ' ' . esc_html($custom_meta) . '</span>';
    }
    
    if( isset( $custom_meta ) ) {
        for ($x = 0; $x <= intval($custom_meta); $x++) {
        $custom_metaimg = $cart_item['data']->get_meta('uploaded_image'.$x);  
          //$cart_item_data[$inputs] = sanitize_text_field( $_POST['uploaded_image'.$x] ); 
          //$item_name .= '<br><span class="custom-meta">' . __('Custom Meta:', 'your-text-domain') . ' ' . esc_html($custom_metaimg) . '</span>';
        }
    }
    return $item_name;
}

/**
 * Add custom cart item data
 */
add_filter( 'woocommerce_add_cart_item_data', 'plugin_republic_add_cart_item_data', 10, 3 ); 
function plugin_republic_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
    
    $rows = get_field('gd_extra_options', $product_id);
    if( $rows ) {
        foreach($rows as $row){
            foreach($row as $rowa){
                $inputs = strtolower(str_replace(' ', '_', $rowa));
                $text_label = $rowa;
                if( isset( $_POST[$inputs] ) ) {
                    $cart_item_data[$inputs] = sanitize_text_field( $_POST[$inputs] );
                }
            }
        }
    }
    
    if( isset( $_POST['image_count'] ) ) {
        for ($x = 0; $x <= $_POST['image_count']-1; $x++) {
          $cart_item_data[$inputs] = sanitize_text_field( $_POST['uploaded_image'.$x] ); 
          $cart_item_data[$inputs] = sanitize_text_field( $_POST['image_count'] ); 
        }
    }
    
    return $cart_item_data;
    
}
/**
 * Display custom item data in the cart and checkout
 */
add_filter( 'woocommerce_get_item_data', 'plugin_republic_get_item_data', 10, 2 ); 
function plugin_republic_get_item_data( $item_data, $cart_item_data ) {
    //echo '<pre>';
    //print_r($cart_item_data['key']);
    //for inputs
    $rows = get_field('gd_extra_options', $cart_item_data['product_id']);
    if( $rows ) {
        foreach($rows as $row){
            foreach($row as $rowa){
                
                $inputs = strtolower(str_replace(' ', '_', $rowa));
                $text_label = $rowa;
                
                if( isset( $cart_item_data[$inputs] ) ) {
                    if($cart_item_data[$inputs] != ''){
                        $item_data[] = array(
                             'key' => $text_label,
                             'value' => wc_clean( $cart_item_data[$inputs] )
                         );
                    }
                }
                
            }
        }
    }
    //For images
    if( $cart_item_data['image_count'] ) {
        for ($x = 0; $x <= $cart_item_data['image_count']; $x++) {
          $item_data[] = array(
                             'key' => 'Imagin',
                             'value' => "<a href='".wp_get_attachment_url($cart_item_data['uploaded_image'.$x])."' target='_blank'>LINK ".$cart_item_data['image_count']."</a>"
                         );
        }
    }    
    return $item_data;
}

add_action('woocommerce_checkout_create_order_line_item', 'save_cart_item_meta_to_order', 10, 4);
function save_cart_item_meta_to_order($item, $cart_item_key, $values, $order) {
    // Check if the item has custom metadata
    if (!empty($values['image_count'])) {
        // Add custom metadata to the order item
        //$item->add_meta_data('Imagin', "<a href='".wp_get_attachment_url($values['uploaded_image'])."' target='_blank'>Link</a>");
        for ($x = 0; $x <= intval($values['image_count'])-1; $x++) {
            $item->add_meta_data('Imagin', "<a href='".wp_get_attachment_url($values['uploaded_image'.$x])."' target='_blank' data-imagecount=".$values['image_count'].">Link</a>");
        }
    }
    
    $product_id = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
    $main_id = wp_get_post_parent_id($product_id);
    $rows = get_field('gd_extra_options', $main_id );
    if( $rows ) {
        foreach($rows as $row){
            foreach($row as $rowa){
                $inputs = strtolower(str_replace(' ', '_', $rowa));
                $text_label = $rowa;
                if( isset( $values[$inputs] ) ) {
                     $item->add_meta_data(
                        $text_label,
                        $values[$inputs],
                        true
                     );
                     
                }
            }
        }
    }
}

Regards,

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.