【问题标题】:Add image file upload field to WooCommerce single productsWooCommerce 单品添加图片文件上传字段
【发布时间】:2021-06-28 16:06:00
【问题描述】:

我创建了一个自定义插件,可以在 woocommerce 单个产品页面中动态显示自定义字段。 显示字段、添加到购物车并添加到订单数据和电子邮件。 但是,我尝试了几天来添加文件上传字段,但没有成功。 该字段显示在前端,如:

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
}

然后添加到购物车,例如:

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;
}

当然,这只是代码的一部分。其余字段都运行良好。是的,如果有人想知道,我只尝试过代码本身。

我已经“玩”了好几天了,但我不知道出了什么问题。 非常感谢任何帮助:)

【问题讨论】:

  • &lt;form&gt; 标签上有enctype="multipart/form-data" 吗?另外,中间是否有可能阻止事物的防火墙?
  • @Chris Haas 我刚刚验证了标签是否存在。我还安装了 wordfence,我只是禁用它以查看是否有变化,但我得到了相同的结果。

标签: php wordpress file-upload woocommerce product


【解决方案1】:

您可以尝试以下操作,将上传的图像数据存储为自定义购物车商品数据并将其保存为自定义订单商品元数据:

// Display additional product fields (+ jQuery code)
add_action( 'woocommerce_before_add_to_cart_button', 'display_additional_product_fields', 9 );
function display_additional_product_fields(){
    ?>
    <p class="form-row validate-required" id="image" >
        <label for="file_field"><?php echo __("Upload Image") . ': '; ?>
            <input type='file' name='image' accept='image/*'>
        </label>
    </p>
    <?php
}


// Add custom fields data as the cart item custom data
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_fields_data_as_custom_cart_item_data', 10, 2 );
function add_custom_fields_data_as_custom_cart_item_data( $cart_item, $product_id ){
    if( isset($_FILES['image']) && ! empty($_FILES['image']) ) {
        $upload       = wp_upload_bits( $_FILES['image']['name'], null, file_get_contents( $_FILES['image']['tmp_name'] ) );
        $filetype     = wp_check_filetype( basename( $upload['file'] ), null );
        $upload_dir   = wp_upload_dir();
        $upl_base_url = is_ssl() ? str_replace('http://', 'https://', $upload_dir['baseurl']) : $upload_dir['baseurl'];
        $base_name    = basename( $upload['file'] );

        $cart_item['file_upload'] = array(
            'guid'      => $upl_base_url .'/'. _wp_relative_upload_path( $upload['file'] ), // Url
            'file_type' => $filetype['type'], // File type
            'file_name' => $base_name, // File name
            'title'     => ucfirst( preg_replace('/\.[^.]+$/', '', $base_name ) ), // Title
        );
        $cart_item['unique_key'] = md5( microtime().rand() ); // Avoid merging items
    }
    return $cart_item;
}

// Display custom cart item data in cart (optional)
add_filter( 'woocommerce_get_item_data', 'display_custom_item_data', 10, 2 );
function display_custom_item_data( $cart_item_data, $cart_item ) {
    if ( isset( $cart_item['file_upload']['title'] ) ){
        $cart_item_data[] = array(
            'name' => __( 'Image uploaded', 'woocommerce' ),
            'value' =>  str_pad($cart_item['file_upload']['title'], 16, 'X', STR_PAD_LEFT) . '…',
        );
    }
    return $cart_item_data;
}

// Save Image data as order item meta data
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_field_update_order_item_meta', 20, 4 );
function custom_field_update_order_item_meta( $item, $cart_item_key, $values, $order ) {
    if ( isset( $values['file_upload'] ) ){
        $item->update_meta_data( '_img_file',  $values['file_upload'] );
    }
}

// Admin orders: Display a linked button + the link of the image file
add_action( 'woocommerce_after_order_itemmeta', 'backend_image_link_after_order_itemmeta', 10, 3 );
function backend_image_link_after_order_itemmeta( $item_id, $item, $product ) {
    // Only in backend for order line items (avoiding errors)
    if( is_admin() && $item->is_type('line_item') && $file_data = $item->get_meta( '_img_file' ) ){
        echo '<p><a href="'.$file_data['guid'].'" target="_blank" class="button">'.__("Open Image") . '</a></p>'; // Optional
        echo '<p><code>'.$file_data['guid'].'</code></p>'; // Optional
    }
}

// Admin new order email: Display a linked button + the link of the image file
add_action( 'woocommerce_email_after_order_table', 'wc_email_new_order_custom_meta_data', 10, 4);
function wc_email_new_order_custom_meta_data( $order, $sent_to_admin, $plain_text, $email ){
    // On "new order" email notifications
    if ( 'new_order' === $email->id ) {
        foreach ($order->get_items() as $item ) {
            if ( $file_data = $item->get_meta( '_img_file' ) ) {
                echo '<p>
                    <a href="'.$file_data['guid'].'" target="_blank" class="button">'.__("Download Image") . '</a><br>
                    <pre><code style="font-size:12px; background-color:#eee; padding:5px;">'.$file_data['guid'].'</code></pre>
                </p><br>';
            }
        }
    }
}

此代码位于活动子主题(或活动主题)的 functions.php 文件中。

在 Woocommerce 版本 4.3.x 中测试并使用所有类型的默认 WooCommerce 产品。

【讨论】:

  • 您的代码也适用于默认的 wordpress 模板(不再适用于 woodmart)谢谢您的努力。
  • 没有人能猜到你是在用魔法使用woodmart模板,所以这个有效的答案通常应该是被接受的。
  • 完全正确。谢谢你花时间帮助我。供参考:woodmart 使用 ajax 添加到购物车,它不支持添加图像。我会尝试调整代码。
  • 如果有多个图像怎么办?
【解决方案2】:

您可以使用诸如产品插件之类的插件来做到这一点

https://woocommerce.com/products/product-add-ons/

这是一个文档链接,该链接专门解释了允许上传文件(它们可以是免费的,也可以是每次上传收费的)

https://docs.woocommerce.com/document/product-add-ons/#section-9

希望这会有所帮助!

【讨论】:

  • 感谢您的回答。不幸的是,插件对我没有帮助,因为它是高度定制的作品。有许多自定义字段根据各种场景动态显示。一切正常,除了文件附件。
【解决方案3】:

我设法找到了与我的模板(woodmart)的冲突 代码在二十和店面完美运行

我应该早点想到这一点,并且一周内不要把头撞到墙上。

【讨论】:

    【解决方案4】:

    如果有人需要,可用于多张图片。

    function add_custom_fields_data_as_custom_cart_item_data($cart_item)
    {
        $images = ['front-image', 'back-image', 'sleeve-image'];
    
        foreach ($images as $image) {
            if (isset($_FILES[$image]) && $_FILES[$image]['error'] === 0) {
    
                $upload       = wp_upload_bits($_FILES[$image]['name'], null, file_get_contents($_FILES[$image]['tmp_name']));
                $filetype     = wp_check_filetype(basename($upload['file']), null);
                $upload_dir   = wp_upload_dir();
                $upl_base_url = is_ssl() ? str_replace('http://', 'https://', $upload_dir['baseurl']) : $upload_dir['baseurl'];
                $base_name    = basename($upload['file']);
    
                $cart_item['file_upload'][] = array(
                    'guid'      => $upl_base_url . '/' . _wp_relative_upload_path($upload['file']), // Url
                    'file_type' => $filetype['type'], // File type
                    'file_name' => uniqid('logo_upload') . $base_name, // File name
                    'title'     => ucfirst(preg_replace('/\.[^.]+$/', '', $base_name)), // Title
                    'position' => $image
                );
                $cart_item['unique_key'] = md5(microtime() . rand()); // Avoid merging items
            }
        }
        return $cart_item;
    }
    add_filter('woocommerce_add_cart_item_data', 'add_custom_fields_data_as_custom_cart_item_data', 10, 3);
    
    
    // Display custom cart item data in cart 
    add_filter('woocommerce_get_item_data', 'display_custom_item_data', 10, 2);
    function display_custom_item_data($cart_item_data, $cart_item)
    {
    
        foreach ($cart_item['file_upload'] as $image) {
            if (isset($image['title'])) {
                $cart_item_data[] = array(
                    'name' => __('Image uploaded', 'woocommerce'),
                    'value' =>  $image['title']
                );
            }
        }
        return $cart_item_data;
    }
    
    // Save Image data as order item meta data
    add_action('woocommerce_checkout_create_order_line_item', 'custom_field_update_order_item_meta', 20, 4);
    function custom_field_update_order_item_meta($item, $cart_item_key, $values, $order)
    {
        if (isset($values['file_upload'])) {
            $item->update_meta_data('_img_files',  $values['file_upload']);
        }
    }
    
    // Admin orders: Display a linked button + the link of the image file
    add_action('woocommerce_after_order_itemmeta', 'backend_image_link_after_order_itemmeta', 10, 3);
    function backend_image_link_after_order_itemmeta($item_id, $item, $product)
    {
        // Only in backend for order line items (avoiding errors)
        if (is_admin() && $item->is_type('line_item') && $files_data = $item->get_meta('_img_files')) {
    
            $imagesHtml = '';
    
            foreach ($files_data as $key => $image) {
                $imagesHtml .= '<p><a href="' . $image['guid'] . '" target="_blank" class="button">' . __($image['position']) . '</a></p>'; // Optional
            }
    
            echo $imagesHtml;
            
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2013-06-21
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      相关资源
      最近更新 更多