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

Woocommerce 后端中的多選字段

Multi Select fields in Woocommerce backend(Woocommerce 后端中的多選字段)
本文介紹了Woocommerce 后端中的多選字段的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我正在嘗試在 Woocommerce 產(chǎn)品變體中創(chuàng)建 4 個多選選項.

例如:我在賣樹,想顯示樹可用的季節(jié).所以我們有 4 個季節(jié)(春、夏、秋、冬),有些樹有兩個或樹的季節(jié).

我將此代碼添加到我的functions.php,但它不會保存選定的選項.當我保存選項并重新加載頁面時,選項再次變?yōu)榭瞻?

我還想知道如何將單個產(chǎn)品頁面(前端)上的選定選項顯示為圖標.

現(xiàn)在,帶有選項的功能適用于產(chǎn)品變體.請查看此屏幕截圖 (具有多選選項的產(chǎn)品變體):

我的代碼:

//添加變化設置add_action('woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3);/*** 創(chuàng)建自定義字段類型**/函數(shù) woocommerce_wp_select_multiple( $field ) {全球 $thepostid, $post, $woocommerce;$thepostid = 空( $thepostid )?$post->ID : $thepostid;$field['class'] = isset( $field['class'] ) ?$field['class'] : '選擇短';$field['wrapper_class'] = isset( $field['wrapper_class'] ) ?$field['wrapper_class'] : '';$field['name'] = isset( $field['name'] ) ?$field['name'] : $field['id'];$field['value'] = isset( $field['value'] ) ?$field['value'] : ( get_post_meta( $thepostid, $field['id'], true ) ? get_post_meta( $thepostid, $field['id'], true ) : array() );echo '<p class="form-field '.esc_attr($field['id']).'_field'.esc_attr($field['wrapper_class']).'"><label for="'. esc_attr( $field['id'] ) . '">'.wp_kses_post( $field['label'] ) .'</label><select id="' . esc_attr( $field['id'] ) . '" name="' . esc_attr( $field['name'] ) . '" class="' .esc_attr( $field['class'] ) . '" multiple="multiple">';foreach ( $field['options'] as $key => $value ) {echo '<option value="' . esc_attr( $key ) . '" ' .( in_array( $key, $field['value'] ) ? 'selected="selected"' : '' ) .'>'.esc_html( $value ) .'</選項>';}回聲'</選擇>';if ( !empty( $field['description'] ) ) {if ( isset( $field['desc_tip'] ) && false !== $field['desc_tip'] ) {echo '<img class="help_tip" data-tip="' . esc_attr( $field['description'] ) . '" src="' . esc_url( WC()->plugin_url() ) . '/assets/images/help.png" height="16" width="16"/>';} 別的 {echo ''.wp_kses_post( $field['description'] ) .'</span>';}}回聲'</p>';}/*** 為變體創(chuàng)建新字段**/函數(shù)variation_settings_fields( $loop, $variation_data, $variation ) {woocommerce_wp_select_multiple(數(shù)組('id' =>'季節(jié)_' .$variation->ID,'類' =>'季節(jié)','標簽' =>__('季節(jié)', 'woocommerce'),'價值' =>get_post_meta( $variation->ID, '_season', true ),'選項' =>大批('春天' =>'春天','夏天' =>'夏天','秋天' =>'秋天','冬天' =>'冬天',)));}add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );函數(shù) save_variation_settings_fields( $post_id ) {$select = $_POST["season_$post_id"];如果(!空($選擇)){update_post_meta( $post_id, '_season', esc_attr( $select ) );}}

解決方案

處理多選字段的可變產(chǎn)品是另一回事,需要進行一些更改才能使其工作.我在以下之后做了 2 個回答:

  1. 第一個產(chǎn)品變體(為您)
  2. 另一個適用于所有其他產(chǎn)品類型

因此在 WooCommerce 后端啟用多選字段的主要功能將是:

function woocommerce_wp_multi_select( $field, $variation_id = 0 ) {全球 $thepostid, $post;如果( $variation_id == 0 )$the_id = 空( $thepostid )?$post->ID : $thepostid;別的$the_id = $variation_id;$field['class'] = isset( $field['class'] ) ?$field['class'] : '選擇短';$field['wrapper_class'] = isset( $field['wrapper_class'] ) ?$field['wrapper_class'] : '';$field['name'] = isset( $field['name'] ) ?$field['name'] : $field['id'];$meta_data = may_unserialize( get_post_meta( $the_id, $field['id'], true ) );$meta_data = $meta_data ?$meta_data : 數(shù)組() ;$field['value'] = isset( $field['value'] ) ?$field['value'] : $meta_data;echo '<p class="form-field ' .esc_attr( $field['id'] ) .'_場地 ' .esc_attr( $field['wrapper_class'] ) .'><label for=''.esc_attr( $field['id'] ) .'>'.wp_kses_post( $field['label'] ) .'</label><select id="'.esc_attr( $field['id'] ) .'"名稱="'.esc_attr( $field['name'] ) .'"類=".esc_attr( $field['class'] ) .'"多個=多個">';foreach ( $field['options'] as $key => $value ) {回聲'<選項值=".esc_attr( $key ) .'"' .( in_array( $key, $field['value'] ) ? 'selected="selected"' : '' ) .'>'.esc_html( $value ) .'</選項>';}回聲'</選擇>';if ( !empty( $field['description'] ) ) {if ( isset( $field['desc_tip'] ) && false !== $field['desc_tip'] ) {echo 'plugin_url()).'/assets/images/help.png';高度=16"寬度=16"/>';} 別的 {echo ''.wp_kses_post( $field['description'] ) .'</span>';}}}

代碼位于活動子主題(或活動主題)的 function.php 文件中.此功能現(xiàn)在將處理任何類型的產(chǎn)品,包括產(chǎn)品變體.

相關(guān):


2).對于所有其他產(chǎn)品類型(除了我們隱藏自定義字段的產(chǎn)品變體):

//為產(chǎn)品常規(guī)選項設置添加自定義字段(對于可變產(chǎn)品隱藏它)add_action('woocommerce_product_options_general_product_data', 'add_custom_settings_fields', 20);函數(shù) add_custom_settings_fields() {全球 $post;echo '

';//隱藏在可變產(chǎn)品中woocommerce_wp_multi_select(數(shù)組('id' =>'_季節(jié)','名稱' =>'_季節(jié)[]','類' =>'','標簽' =>__('季節(jié)', 'woocommerce'),'選項' =>大批('春天' =>__(春天",woocommerce"),'夏天' =>__(夏天",woocommerce"),'秋天' =>__(秋天",woocommerce"),'冬天' =>__(冬天",woocommerce"),)) );回聲'</div>';}//在后端提交時將自定義多選字段保存到數(shù)據(jù)庫(對于所有其他產(chǎn)品類型)add_action( 'woocommerce_process_product_meta', 'save_product_options_custom_fields', 30, 1 );函數(shù) save_product_options_custom_fields( $post_id ){if( isset( $_POST['_season'] ) ){$post_data = $_POST['_season'];//多數(shù)據(jù)清理$sanitize_data = array();if( is_array($post_data) && sizeof($post_data) > 0 ){foreach( $post_data 作為 $value ){$sanitize_data[] = esc_attr( $value );}}update_post_meta( $post_id, '_season', $sanitize_data );}}

代碼位于活動子主題(或活動主題)的 function.php 文件中.經(jīng)測試有效.

I am trying to create 4 multi-select options at Woocommerce product variations.

For example: I am selling trees and want to display the season the tree is available. So we have 4 seasons (spring, summer, autumn, winter), Some trees are available in two or tree seasons.

I added this code to my functions.php, but it won't save the selected options. When i save the option and reload the page the options are blank again.

And I was also wondering how to show the selected options on the single product page (frontend) as icon.

For now the function with the options works at the product variations. Please see this screenshot (product variation with multi select options):

My code:

// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );

/**
 * Create custom field type
 *
*/
function woocommerce_wp_select_multiple( $field ) {
    global $thepostid, $post, $woocommerce;

    $thepostid              = empty( $thepostid ) ? $post->ID : $thepostid;
    $field['class']         = isset( $field['class'] ) ? $field['class'] : 'select short';
    $field['wrapper_class'] = isset( $field['wrapper_class'] ) ? $field['wrapper_class'] : '';
    $field['name']          = isset( $field['name'] ) ? $field['name'] : $field['id'];
    $field['value']         = isset( $field['value'] ) ? $field['value'] : ( get_post_meta( $thepostid, $field['id'], true ) ? get_post_meta( $thepostid, $field['id'], true ) : array() );

    echo '<p class="form-field ' . esc_attr( $field['id'] ) . '_field ' . esc_attr( $field['wrapper_class'] ) . '"><label for="' . esc_attr( $field['id'] ) . '">' . wp_kses_post( $field['label'] ) . '</label><select id="' . esc_attr( $field['id'] ) . '" name="' . esc_attr( $field['name'] ) . '" class="' . esc_attr( $field['class'] ) . '" multiple="multiple">';

    foreach ( $field['options'] as $key => $value ) {

        echo '<option value="' . esc_attr( $key ) . '" ' . ( in_array( $key, $field['value'] ) ? 'selected="selected"' : '' ) . '>' . esc_html( $value ) . '</option>';

    }

    echo '</select> ';

    if ( ! empty( $field['description'] ) ) {

        if ( isset( $field['desc_tip'] ) && false !== $field['desc_tip'] ) {
            echo '<img class="help_tip" data-tip="' . esc_attr( $field['description'] ) . '" src="' . esc_url( WC()->plugin_url() ) . '/assets/images/help.png" height="16" width="16" />';
        } else {
            echo '<span class="description">' . wp_kses_post( $field['description'] ) . '</span>';
        }

    }
    echo '</p>';
}


/**
 * Create new fields for variations
 *
*/
function variation_settings_fields( $loop, $variation_data, $variation ) {

    woocommerce_wp_select_multiple( array(
        'id' => 'season_' . $variation->ID,
        'class' => 'season',
        'label' => __('Season', 'woocommerce'),
        'value' => get_post_meta( $variation->ID, '_season', true ),
        'options' => array(
            'spring' => 'Spring',
            'summer' => 'Summer',
            'autumn' => 'Autumn',
            'winter' => 'Winter',
        ))
    );
}

add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
function save_variation_settings_fields( $post_id ) {

    $select = $_POST["season_$post_id"];
    if( ! empty( $select ) ) {
        update_post_meta( $post_id, '_season', esc_attr( $select ) );
    }
}   

解決方案

To handle variable products for multi select fields is another thing and some changes need to be done to make it work. I have made 2 answers after below:

  1. The first one for product variations (for you)
  2. The other one for all other product types

So the main function that enable multi-select fields in WooCommerce backend will be:

function woocommerce_wp_multi_select( $field, $variation_id = 0 ) {
    global $thepostid, $post;

    if( $variation_id == 0 )
        $the_id = empty( $thepostid ) ? $post->ID : $thepostid;
    else
        $the_id = $variation_id;

    $field['class']         = isset( $field['class'] ) ? $field['class'] : 'select short';
    $field['wrapper_class'] = isset( $field['wrapper_class'] ) ? $field['wrapper_class'] : '';
    $field['name']          = isset( $field['name'] ) ? $field['name'] : $field['id'];

    $meta_data              = maybe_unserialize( get_post_meta( $the_id, $field['id'], true ) );
    $meta_data              = $meta_data ? $meta_data : array() ;

    $field['value'] = isset( $field['value'] ) ? $field['value'] : $meta_data;

    echo '<p class="form-field ' . esc_attr( $field['id'] ) . '_field ' . esc_attr( $field['wrapper_class'] ) . '"><label for="' . esc_attr( $field['id'] ) . '">' . wp_kses_post( $field['label'] ) . '</label><select id="' . esc_attr( $field['id'] ) . '" name="' . esc_attr( $field['name'] ) . '" class="' . esc_attr( $field['class'] ) . '" multiple="multiple">';

    foreach ( $field['options'] as $key => $value ) {
        echo '<option value="' . esc_attr( $key ) . '" ' . ( in_array( $key, $field['value'] ) ? 'selected="selected"' : '' ) . '>' . esc_html( $value ) . '</option>';
    }
    echo '</select> ';
    if ( ! empty( $field['description'] ) ) {
        if ( isset( $field['desc_tip'] ) && false !== $field['desc_tip'] ) {
            echo '<img class="help_tip" data-tip="' . esc_attr( $field['description'] ) . '" src="' . esc_url( WC()->plugin_url() ) . '/assets/images/help.png" height="16" width="16" />';
        } else {
            echo '<span class="description">' . wp_kses_post( $field['description'] ) . '</span>';
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). This function, will handle now any type of products, including product variations.

Related: Multi checkbox fields in Woocommerce backend


1). For product variations (for you):

// Add custom multi-select fields in variation setting tab
add_action( 'woocommerce_product_after_variable_attributes', 'add_variation_settings_fields', 20, 3 );
function add_variation_settings_fields( $loop, $variation_data, $variation_post ) {

    woocommerce_wp_multi_select( array(
        'id' => '_season',
        'name' => '_season['.$loop.'][]',
        'class' => '',
        'label' => __('Season', 'woocommerce'),
        'options' => array(
            'spring' => __("Spring", "woocommerce"),
            'summer' => __("Summer", "woocommerce"),
            'autumn' => __("Autumn", "woocommerce"),
            'winter' => __("Winter", "woocommerce"),
        )
    ), $variation_post->ID );
}

// Save custom multi-select fields for variations
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
function save_variation_settings_fields( $variation_id, $i ) {
    if( isset( $_POST['_season'][$i] ) ){
        $post_data = $_POST['_season'][$i];
        // Multi data sanitization 
        $sanitize_data = array();
        if( is_array($post_data) && sizeof($post_data) > 0 ){
            foreach( $post_data as $value ){
                $sanitize_data[] = esc_attr( $value );
            }
        }
        update_post_meta( $variation_id, '_season', $sanitize_data );
    }

}

Code goes in function.php file of your active child theme (or active theme). Tested and works.



2). For all other product types (except product variations, where we hide that custom field):

// Add custom fields for product general option settings (hidding it for variable products)
add_action( 'woocommerce_product_options_general_product_data', 'add_custom_settings_fields', 20 );
function add_custom_settings_fields() {
    global $post;

    echo '<div class="options_group hide_if_variable"">'; // Hidding in variable products

    woocommerce_wp_multi_select( array(
        'id' => '_season',
        'name' => '_season[]',
        'class' => '',
        'label' => __('Season', 'woocommerce'),
        'options' => array(
            'spring' => __("Spring", "woocommerce"),
            'summer' => __("Summer", "woocommerce"),
            'autumn' => __("Autumn", "woocommerce"),
            'winter' => __("Winter", "woocommerce"),
        )
    ) );

    echo '</div>';
}

// Save custom multi-select fields to database when submitted in Backend (for all other product types)
add_action( 'woocommerce_process_product_meta', 'save_product_options_custom_fields', 30, 1 );
function save_product_options_custom_fields( $post_id ){
    if( isset( $_POST['_season'] ) ){
        $post_data = $_POST['_season'];
        // Multi data sanitization 
        $sanitize_data = array();
        if( is_array($post_data) && sizeof($post_data) > 0 ){
            foreach( $post_data as $value ){
                $sanitize_data[] = esc_attr( $value );
            }
        }
        update_post_meta( $post_id, '_season', $sanitize_data );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

這篇關(guān)于Woocommerce 后端中的多選字段的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(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 和電話字段驗證問題中添加自定義注冊字段)
Add a select field that will change price in Woocommerce simple products(在 Woocommerce 簡單產(chǎn)品中添加一個將更改價格的選擇字段)
Add custom columns to admin products list in WooCommerce 3(在 WooCommerce 3 中將自定義列添加到管理產(chǎn)品列表)
Customizing checkout quot;Place Orderquot; button output html(自定義結(jié)帳“下訂單按鈕輸出html)
主站蜘蛛池模板: 单螺旋速冻机-双螺旋-流态化-隧道式-食品速冻机厂家-广州冰泉制冷 | 电动高尔夫球车|电动观光车|电动巡逻车|电动越野车厂家-绿友机械集团股份有限公司 | 四合院设计_四合院装修_四合院会所设计-四合院古建设计与建造中心1 | 网站建设,北京网站建设,北京网站建设公司,网站系统开发,北京网站制作公司,响应式网站,做网站公司,海淀做网站,朝阳做网站,昌平做网站,建站公司 | 企业管理培训,企业培训公开课,企业内训课程,企业培训师 - 名课堂企业管理培训网 | YJLV22铝芯铠装电缆-MYPTJ矿用高压橡套电缆-天津市电缆总厂 | 展厅装修公司|企业展厅设计|展厅制作|展厅搭建—广州展厅装饰公司 | 解放卡车|出口|济南重汽|报价大全|山东三维商贸有限公司 | 交通信号灯生产厂家_红绿灯厂家_电子警察监控杆_标志杆厂家-沃霖电子科技 | 工业PH计|工业ph酸度计|在线PH计价格-合肥卓尔仪器仪表有限公司 济南画室培训-美术高考培训-山东艺霖艺术培训画室 | 真空泵维修保养,普发,阿尔卡特,荏原,卡西亚玛,莱宝,爱德华干式螺杆真空泵维修-东莞比其尔真空机电设备有限公司 | 烟气在线监测系统_烟气在线监测仪_扬尘检测仪_空气质量监测站「山东风途物联网」 | 航空铝型材,7系铝型材挤压,硬质阳*氧化-余润铝制品 | 定量包装秤,吨袋包装称,伸缩溜管,全自动包装秤,码垛机器人,无锡市邦尧机械工程有限公司 | 照相馆预约系统,微信公众号摄影门店系统,影楼管理软件-盟百网络 | 考勤系统_人事考勤管理系统_本地部署BS考勤系统_考勤软件_天时考勤管理专家 | 高楼航空障碍灯厂家哪家好_航空障碍灯厂家_广州北斗星障碍灯有限公司 | 单级/双级旋片式真空泵厂家,2xz旋片真空泵-浙江台州求精真空泵有限公司 | 袋式过滤器,自清洗过滤器,保安过滤器,篮式过滤器,气体过滤器,全自动过滤器,反冲洗过滤器,管道过滤器,无锡驰业环保科技有限公司 | YJLV22铝芯铠装电缆-MYPTJ矿用高压橡套电缆-天津市电缆总厂 | 5L旋转蒸发器-20L-50L旋转蒸发器-上海越众仪器设备有限公司 | 福州时代广告制作装饰有限公司-福州广告公司广告牌制作,福州展厅文化墙广告设计, | 数控专用机床,专用机床,自动线,组合机床,动力头,自动化加工生产线,江苏海鑫机床有限公司 | 上海单片机培训|重庆曙海培训分支机构—CortexM3+uC/OS培训班,北京linux培训,Windows驱动开发培训|上海IC版图设计,西安linux培训,北京汽车电子EMC培训,ARM培训,MTK培训,Android培训 | 开云(中国)Kaiyun·官方网站 - 登录入口 | 密度电子天平-内校-外校电子天平-沈阳龙腾电子有限公司 | 爆破器材运输车|烟花爆竹运输车|1-9类危险品厢式运输车|湖北江南专用特种汽车有限公司 | 一体化污水处理设备_生活污水处理设备_全自动加药装置厂家-明基环保 | 高铝轻质保温砖_刚玉莫来石砖厂家_轻质耐火砖价格| 板式换热器_板式换热器价格_管式换热器厂家-青岛康景辉 | 温州在线网| 压接机|高精度压接机|手动压接机|昆明可耐特科技有限公司[官网] 胶泥瓷砖胶,轻质粉刷石膏,嵌缝石膏厂家,腻子粉批发,永康家德兴,永康市家德兴建材厂 | 美国HASKEL增压泵-伊莱科elettrotec流量开关-上海方未机械设备有限公司 | ET3000双钳形接地电阻测试仪_ZSR10A直流_SXJS-IV智能_SX-9000全自动油介质损耗测试仪-上海康登 | HYDAC过滤器,HYDAC滤芯,现货ATOS油泵,ATOS比例阀-东莞市广联自动化科技有限公司 | 北京发电车出租-发电机租赁公司-柴油发电机厂家 - 北京明旺盛安机电设备有限公司 | 雷蒙磨,雷蒙磨粉机,雷蒙磨机 - 巩义市大峪沟高峰机械厂 | 工业淬火油烟净化器,北京油烟净化器厂家,热处理油烟净化器-北京众鑫百科 | 河南砖机首页-全自动液压免烧砖机,小型砌块水泥砖机厂家[十年老厂] | 翻斗式矿车|固定式矿车|曲轨侧卸式矿车|梭式矿车|矿车配件-山东卓力矿车生产厂家 | 3D全息投影_地面互动投影_360度立体投影_水幕灯光秀 | 广东银虎 蜂窝块状沸石分子筛-吸附脱硫分子筛-萍乡市捷龙环保科技有限公司 |