pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

WooCommerce單品添加圖片文件上傳字段

Add image file upload field to WooCommerce single products(WooCommerce單品添加圖片文件上傳字段)
本文介紹了WooCommerce單品添加圖片文件上傳字段的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!

問題描述

限時(shí)送ChatGPT賬號(hào)..

我創(chuàng)建了一個(gè)自定義插件,可在 woocommerce 單個(gè)產(chǎn)品頁(yè)面中動(dòng)態(tài)顯示自定義字段.字段顯示、添加到購(gòu)物車和添加到訂單數(shù)據(jù)和電子郵件.但是,我嘗試了好幾天來(lái)添加文件上傳字段,但沒有運(yùn)氣.該字段顯示在前端,如:

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
}

然后添加到購(gòu)物車中:

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

當(dāng)然,這只是代碼的一部分.其余字段工作正常.是的,如果有人想知道,我只嘗試過代碼本身.

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 :)

推薦答案

您可以嘗試以下操作,將上傳的圖像數(shù)據(jù)存儲(chǔ)為自定義購(gòu)物車項(xiàng)目數(shù)據(jù)并將其保存為自定義訂單項(xiàng)目元數(shù)據(jù):

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:

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

此代碼位于活動(dòng)子主題(或活動(dòng)主題)的 functions.php 文件中.

This code goes in functions.php file of your active child theme (or active theme).

在 Woocommerce 4.3.x 版中進(jìn)行測(cè)試,可與所有類型的默認(rèn) WooCommerce 產(chǎn)品配合使用.

Tested in Woocommerce version 4.3.x and working with default WooCommerce products from all types.

這篇關(guān)于WooCommerce單品添加圖片文件上傳字段的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

Add programmatically a downloadable file to Woocommerce products(以編程方式將可下載文件添加到 Woocommerce 產(chǎn)品)
Get today#39;s total orders count for each product in Woocommerce(獲取今天 Woocommerce 中每種產(chǎn)品的總訂單數(shù))
Add Custom registration fields in WooCommerce and phone field validation issue(在 WooCommerce 和電話字段驗(yàn)證問題中添加自定義注冊(cè)字段)
Add a select field that will change price in Woocommerce simple products(在 Woocommerce 簡(jiǎn)單產(chǎn)品中添加一個(gè)將更改價(jià)格的選擇字段)
Add custom columns to admin products list in WooCommerce 3(在 WooCommerce 3 中將自定義列添加到管理產(chǎn)品列表)
Customizing checkout quot;Place Orderquot; button output html(自定義結(jié)帳“下訂單按鈕輸出html)
主站蜘蛛池模板: 酒精检测棒,数显温湿度计,酒安酒精测试仪,酒精检测仪,呼气式酒精检测仪-郑州欧诺仪器有限公司 | 手术示教系统-数字化手术室系统-林之硕医疗云智能视频平台 | 高中学习网-高考生信息学习必备平台| 工控机,嵌入式主板,工业主板,arm主板,图像采集卡,poe网卡,朗锐智科 | 集装袋吨袋生产厂家-噸袋廠傢-塑料编织袋-纸塑复合袋-二手吨袋-太空袋-曹县建烨包装 | 电动高尔夫球车|电动观光车|电动巡逻车|电动越野车厂家-绿友机械集团股份有限公司 | Trimos测长机_测高仪_TESA_mahr,WYLER水平仪,PWB对刀仪-德瑞华测量技术(苏州)有限公司 | 广东恩亿梯电源有限公司【官网】_UPS不间断电源|EPS应急电源|模块化机房|电动汽车充电桩_UPS电源厂家(恩亿梯UPS电源,UPS不间断电源,不间断电源UPS) | 印刷人才网 印刷、包装、造纸,中国80%的印刷企业人才招聘选印刷人才网! | 重庆监控_电子围栏设备安装公司_门禁停车场管理系统-劲浪科技公司 | 舞台木地板厂家_体育运动木地板_室内篮球馆木地板_实木运动地板厂家_欧氏篮球地板推荐 | 武汉高低温试验机-现货恒温恒湿试验箱-高低温湿热交变箱价格-湖北高天试验设备 | 博莱特空压机|博莱特-阿特拉斯独资空压机品牌核心代理商 | Trimos测长机_测高仪_TESA_mahr,WYLER水平仪,PWB对刀仪-德瑞华测量技术(苏州)有限公司 | 刺绳_刀片刺网_刺丝滚笼_不锈钢刺绳生产厂家_安平县浩荣金属丝网制品有限公司-安平县浩荣金属丝网制品有限公司 | 北京企业宣传片拍摄_公司宣传片制作-广告短视频制作_北京宣传片拍摄公司 | 登车桥动力单元-非标液压泵站-非标液压系统-深圳市三好科技有限公司 | b2b网站大全,b2b网站排名,找b2b网站就上地球网 | 涂层测厚仪_漆膜仪_光学透过率仪_十大创新厂家-果欧电子科技公司 | 螺杆真空泵_耐腐蚀螺杆真空泵_水环真空泵_真空机组_烟台真空泵-烟台斯凯威真空 | 【化妆品备案】进口化妆品备案流程-深圳美尚美化妆品有限公司 | 河南生物显微镜,全自动冰冻切片机-河南荣程联合科技有限公司 | Magnescale探规,Magnescale磁栅尺,Magnescale传感器,Magnescale测厚仪,Mitutoyo光栅尺,笔式位移传感器-苏州连达精密量仪有限公司 | led太阳能路灯厂家价格_风光互补庭院灯_农村市政工程路灯-中山华可路灯品牌 | 电动手术床,医用护理床,led手术无影灯-曲阜明辉医疗设备有限公司 | 新能源汽车电池软连接,铜铝复合膜柔性连接,电力母排-容发智能科技(无锡)有限公司 | 经济师考试_2025中级经济师报名时间_报名入口_考试时间_华课网校经济师培训网站 | 色油机-色母机-失重|称重式混料机-称重机-米重机-拌料机-[东莞同锐机械]精密计量科技制造商 | 新疆乌鲁木齐网站建设-乌鲁木齐网站制作设计-新疆远璨网络 | 土壤墒情监测站_土壤墒情监测仪_土壤墒情监测系统_管式土壤墒情站-山东风途物联网 | 水平筛厂家-三轴椭圆水平振动筛-泥沙震动筛设备_山东奥凯诺矿机 包装设计公司,产品包装设计|包装制作,包装盒定制厂家-汇包装【官方网站】 | 废气处理_废气处理设备_工业废气处理_江苏龙泰环保设备制造有限公司 | 点胶机_点胶阀_自动点胶机_智能点胶机_喷胶机_点胶机厂家【欧力克斯】 | 999范文网_优质范文下载写作帮手| 自进式锚杆-自钻式中空注浆锚杆-洛阳恒诺锚固锚杆生产厂家 | 精密模具制造,注塑加工,吹塑和吹瓶加工,EPS泡沫包装生产 - 济南兴田塑胶有限公司 | 佛山市钱丰金属不锈钢蜂窝板定制厂家|不锈钢装饰线条|不锈钢屏风| 电梯装饰板|不锈钢蜂窝板不锈钢工艺板材厂家佛山市钱丰金属制品有限公司 | 周口风机|周风风机|河南省周口通用风机厂 | 环氧树脂地坪_防静电地坪漆_环氧地坪漆涂料厂家-地壹涂料地坪漆 环球电气之家-中国专业电气电子产品行业服务网站! | 精密五金加工厂-CNC数控车床加工_冲压件|蜗杆|螺杆加工「新锦泰」 | 圆形振动筛_圆筛_旋振筛_三次元振动筛-河南新乡德诚生产厂家 |