在 WooCommerce 中随处保存并显示产品选择的自定义数据

2023-12-26

我有一个代码显示产品编辑页面上的复选框。当我单击此复选框时,单个产品页面上会显示一个选择框。

这是我的代码:

// Display Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'roast_custom_field_add');
function roast_custom_field_add(){
    global $post;

    // Checkbox
    woocommerce_wp_checkbox( 
        array( 
            'id' => '_roast_checkbox', 
            'label' => __('Roast Level', 'woocommerce' ), 
            'description' => __( 'Enable roast level!', 'woocommerce' ) 
        )
    ); 
}

// Save Checkbox Field
add_action('woocommerce_process_product_meta', 'roast_custom_field_save');
function roast_custom_field_save($post_id){
    // Custom Product Checkbox Field
    $roast_checkbox = isset( $_POST['_roast_checkbox'] ) ? 'yes' : 'no';
    update_post_meta($post_id, '_roast_checkbox', esc_attr( $roast_checkbox ));
}

// Display Select Box
add_action( 'woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0 );
function add_roast_custom_field() {
    global $post;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if ( is_product() && get_post_meta( $post->ID, '_roast_checkbox', true ) == 'yes' ) {

        echo '<div>';

        woocommerce_form_field( 'roast_custom_options', array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Roast Level'),        
            'required'      => false,
            'options'   => array( 
                ''      => 'Please select', 
                'Blue'  => 'Blue', 
                'Rare'  => 'Rare',
                'Medium Rare'   => 'Medium Rare',
                'Medium'    => 'Medium',
                'Medium Well'   => 'Medium Well',
                'Well Done' => 'Well Done'
            )
        ), '' );

        echo '</div>';
    }
}

当您单击该复选框时,选择字段将正确显示。

但选择选项后的数据不会保存。

此外,这些数据不会显示在购物车页面、结帐页面、订单等上。

这是我的代码:

// Save roast custom field
add_action( 'woocommerce_add_to_cart', 'roast_custom_field_add_to_cart', 20, 6 );
function roast_custom_field_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){

    if( isset($_POST['roast_custom_options']) ){
        $roast_values   = (array) get_post_meta( $product_id, '_roast_custom_options_values', true );
        $roast_values[] = sanitize_text_field( $_POST['roast_custom_options'] );
        update_post_meta( $product_id, '_roast_custom_options_values', $roast_values );
    }
}

// Add custom fields values under cart item name in cart
add_filter( 'woocommerce_cart_item_name', 'roast_custom_field', 10, 3 );
function roast_custom_field( $item_name, $cart_item, $cart_item_key ) {
    if( ! is_cart() )
        return $item_name;

    if( $roast_values = $cart_item['data']->get_meta('_roast_custom_options_values') ) {
        $item_name .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $roast_values . ' </div>';
    }   
    return $item_name;
}

// Display roast custom fields values under item name in checkout
add_filter( 'woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3 );
function roast_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
    if( $roast_values = $cart_item['data']->get_meta('_roast_custom_options_values') ) {
        $item_qty .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $roast_values . ' </div>';
    }
    return $item_qty;
}

// Display roast custom fields values on orders and email notifications
add_filter( 'woocommerce_order_item_name', 'roast_custom_order_item_name', 10, 2 );
function roast_custom_order_item_name( $item_name, $item ) {
    $product = $item->get_product();

    if( $roast_values = $product->get_meta('_roast_custom_options_values') ) {
        $item_name .= '<br /><span class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $roast_values . ' </span>';
    }
    return $item_name;
}

如何修复代码以使一切正常工作?


我“匆忙”重新审视了你的代码,还添加了一些缺失的功能并删除了另一个:

// Display Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'roast_custom_field_add');
function roast_custom_field_add(){
    global $post;

    // Checkbox
    woocommerce_wp_checkbox(
        array(
            'id' => '_roast_checkbox',
            'label' => __('Roast Level', 'woocommerce' ),
            'description' => __( 'Enable roast level!', 'woocommerce' )
        )
    );
}

// Save Checkbox Field
add_action('woocommerce_process_product_meta', 'roast_custom_field_save');
function roast_custom_field_save($post_id){
    // Custom Product Checkbox Field
    $roast_checkbox = isset( $_POST['_roast_checkbox'] ) ? 'yes' : 'no';
    update_post_meta($post_id, '_roast_checkbox', esc_attr( $roast_checkbox ));
}

// Display Select Box
add_action( 'woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0 );
function add_roast_custom_field() {
    global $product;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if ( is_product() && $product->get_meta( '_roast_checkbox' ) === 'yes' ) {

        echo '<div>';

        woocommerce_form_field( 'roast_custom_options', array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Roast Level'),
            'required'      => false,
            'options'   => array(
                ''      => 'Please select',
                'Blue'  => 'Blue',
                'Rare'  => 'Rare',
                'Medium Rare'   => 'Medium Rare',
                'Medium'    => 'Medium',
                'Medium Well'   => 'Medium Well',
                'Well Done' => 'Well Done'
            )
        ), '' );

        echo '</div>';
    }
}

// Add as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 3 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){
    if( isset( $_POST['roast_custom_options'] ) ) {
        $cart_item_data['roast_option'] = wc_clean( $_POST['roast_custom_options'] );
    }
    return $cart_item_data;
}

// Add custom fields values under cart item name in cart
add_filter( 'woocommerce_cart_item_name', 'roast_custom_field', 10, 3 );
function roast_custom_field( $item_name, $cart_item, $cart_item_key ) {
    if( ! is_cart() )
        return $item_name;

    if( isset($cart_item['roast_option']) ) {
        $item_name .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . '</div>';
    }
    return $item_name;
}

// Display roast custom fields values under item name in checkout
add_filter( 'woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3 );
function roast_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
    if( isset($cart_item['roast_option']) ) {
        $item_qty .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . 'гр.</div>';
    }
    return $item_qty;
}

// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4 );
function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order ) {
    if( isset($values['roast_option']) ) {
        $key = __('Roast Level', 'woocommerce');
        $value = $values['roast_option'];
        $item->update_meta_data( $key, $value );
    }
}

代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。

在前端购物车页面上:

在后台订单编辑页面:

关于电子邮件通知:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 WooCommerce 中随处保存并显示产品选择的自定义数据 的相关文章

  • 如何检查号码是否是巴基斯坦用户的手机号码而不是固定电话号码

    我所做的是从开头删除 92 或 0092 并使用以下代码检查它是否是巴基斯坦人的有效手机号码 if preg match 3 0 4 0 9 number 1 Pakistani mobile number else not a pakis
  • PHP 文件上传帮助

    div align center div 这是我的代码
  • 使用 md5 加密的 PHP 和 Mysql 查询出现问题

    我使用普通的 php mysql 插入查询并使用 md5 加密密码 这是插入查询 sql mysql query INSERT INTO user username password role approved values usernam
  • PHPExcel下载文件

    我想下载使用 PHPExcel 生成的 Excel 文件 我按照以下代码PHPExcel 强制下载问题 https stackoverflow com questions 26265108 phpexcel force download i
  • 为什么AES java解密返回额外的字符?

    请原谅我英语不好 我使用 mcrypt 我从这里得到它用于 php 和 java 的 MCrypt https snipt net raw ee573b6957b7416f28aa560ead71c3a2 nice 在我的android应用
  • 覆盖供应商自动加载编辑器

    有没有办法让您创建的自动加载文件在调用供应商自动加载之前运行 我们似乎遇到了 SimpleSAML 的自动加载覆盖我们创建的自动加载文件之一的问题 我是 Composer 的新手 似乎无法在网上找到任何解决方案 我尝试将我们的自动加载文件包
  • 如何在MAMP中设置环境变量?

    如何在 MAMP 版本 3 3 中设置环境变量 我可以在我的 PHP 应用程序中使用它 我已经更新了 Applications MAMP Library bin envvars and envvars std file并添加以下行 Lice
  • session_regenerate_id 没有创建新的会话 id

    我有一个脚本 旨在完成当前会话并开始新的会话 我使用了一段代码 它在我的开发计算机上运行良好 但是 当我将其发布到生产服务器时 会话 ID 始终保持不变 以下是我重新启动会话的代码 session start SESSION array P
  • TOMCAT 6 中的 PHP - 异常

    我一直在努力融入PHP in APACHE TOMCAT 6依照指示second answer为了QUESTION https stackoverflow com questions 779246 run a php app using t
  • 使用 PHP 的 Google Glass GDK 身份验证

    我正在尝试点击此链接来验证 GDK 中的用户 https developers google com glass develop gdk authentication https developers google com glass de
  • 如何将 mysql 转换为 mysqli? [复制]

    这个问题在这里已经有答案了 我厌倦了将 mysql 转换为 mysqli 但似乎收到了很多错误和警告 连接到数据库没有问题 但其余代码似乎错误 我做错了什么 sql
  • Laravel 5.2 带有可变参数的命名路由用法

    我有这样的路线 Open New Subscription page Route get account subscriptions create menu uses gt Subscriptions SubscriptionControl
  • PHP 中的 NOW() 函数

    是否有 PHP 函数以与 MySQL 函数相同的格式返回日期和时间NOW 我知道如何使用date 但我想问是否有专门用于此的功能 例如 返回 2009 12 01 00 00 00 您可以使用date https www php net m
  • 在 Woocommerce 购物车中设置最小小计金额

    我正在尝试将最低订单金额设置为 25 美元 到目前为止 我找到了这段代码 如果未达到最低限度 它似乎可以阻止结账 但它使用的小计包含税费 我需要在总计中排除税费 add action woocommerce checkout process
  • 如何编写在正文中包含锚标记的 Zend Framework URL?

    使用 Zend Framework 中设置的标准 MVC 我希望能够显示始终具有锚点的页面 现在我只是在 phtml 文件中添加一个带有 anchor 的无意义参数
  • PHP中如何识别服务器IP地址

    PHP中如何识别服务器IP地址 对于服务器 ip 来说是这样的 SERVER SERVER ADDR 这是港口的 SERVER SERVER PORT
  • 使用 DOJO 自动完成文本框

    我正在寻找一种使用 DOJO 进行文本框自动建议的简单方法 我将查询的数据库表 使用 PHP 脚本 以 JSON 形式返回 有超过 100 000 条记录 因此这确实不应该采用 FilteringSelect 或 ComboBox 的形式
  • 如何在php中使用preg添加html属性

    我正在寻找在 php 中编写一个脚本来扫描 html 文档并根据它找到的内容向元素添加新标记 更具体地说 我是扫描文档并为每个元素搜索CSS标记 float right left 如果找到它 它会添加align right left 基于它
  • 如何在 codeigniter 查询中使用 FIND_IN_SET?

    array array classesID gt 6 this gt db gt select gt from this gt table name gt where array gt order by this gt order by q
  • mysqli bind_param 中的 NULL 是什么类型?

    我正在尝试将参数绑定到 INSERT INTO MySQLi 准备好的语句 如果该变量存在 否则插入 null 然后我知道 type variable i corresponding variable has type integer d

随机推荐

  • 为什么对依赖单例的系统进行单元测试很困难?

    我读过支持和反对使用单例模式的案例 一种常见的反对案例描述了单例单元测试的困难 但我不清楚这是为什么 如果单元测试是构建的一部分 您难道不能只引用单例并在需要时使用它吗 我从java的角度思考 但我想这不重要 关于此的一篇很棒的文章是单身人
  • C 和 C++ 中的静态变量

    声明为的变量之间有什么区别吗static在 C 和 C 之间的任何函数之外 我读到了static意味着文件范围和变量在文件之外不可访问 我还读到 在 C 中 全局变量是static 那么这是否意味着C中的全局变量不能在另一个文件中访问 不
  • 使用 foreach 循环来初始化变量

    我构建了一个空关联数组 其键名引用提交的帖子数据 我可以很好地捕获后数据 但在尝试实例化名称与数组键匹配的变量时遇到了麻烦 例如 insArray array rUsername gt rPass gt rQuestion gt rAnsw
  • 永久修改启动 Activity 的 Intent

    我想发送一个意图来启动一个活动 我希望能够修改该意图 然后 当活动被销毁并重新创建时 我希望当我调用时这些修改仍然存在getIntent 目前 只要 Activity 没有被销毁 修改意图就可以正常工作 如果有 那么当重新创建 Activi
  • 根据拖放位置对 firestore 中的文档进行排序

    我的目标是呈现我的LinkContainer组件 以便它们位于我的拖放上下文中
  • 如何修复 MSSQL 上的“无效列名”SQL 异常

    我试图在运行时传递要在代码中检查的列名称和值 不过我得到的是 无效的列名 例外 代码如下 cmd new SqlCommand con Open cmd Connection con cmd CommandText INSERT INTO
  • ASP.NET MVC3 RC2 不工作

    我的输入装饰如下
  • 如何获取 Java Hashmap 上冲突数量的指标?

    我正在实现一个自定义哈希函数 如果我在 HashMap 存储桶中发生多次冲突 我如何知道存储桶中存储了多少元素 API 中没有对此直接支持 成员变量table用于存储存储桶的 甚至不是公共的 因此扩展该类不会让您走得太远 假设您正在评估哈希
  • 从数据列表中选择项目时,为什么值末尾的空格会消失?

    我遇到了一个奇怪的问题 当使用数据列表时 值末尾的空格消失了 这让我想知道为什么 我使用的是谷歌浏览器 我可以确保末尾的空格将包含在 通过将最终结果分配给值属性 而不是介于
  • CSS中first-line和first-child的特殊性?

    我有以下 html 代码 p asdasdasdsad br sdfsdfs p 输出是 asdasdasdasd sdfsdfs 但是 我的想法是 p 标签是 body 的第一个子标签 first child 是一个伪类 其特异性为 10
  • $authWithPassword 不是 AngularFire 2.x 中的函数

    我以前看过有关此问题的帖子 但它们要么已经过时 要么提供与我的设置非常相似的解决方案 基本上 我的控制器中有两个函数 authCtrl login 和 authCtrl register 寄存器对 Auth createUserWithEm
  • javascript 相当于 java 的 Map.getKey()

    我有一个地图 或者说 JavaScript 中的关联数组类型的结构 var myMap one 1 two 2 three 3 要获取与给定值相对应的键 我必须迭代映射 function map test value var myMap o
  • 删除 Mac 上的 Qt 库

    我想删除已安装的 Qt 4 8 库并在我的 Mac 上安装 Qt 4 6 库 但是当我尝试安装它们时 我得到 Qt 库无法安装在此磁盘上 较新版本的 该软件已存在于该磁盘上 我删除了 usr local Qt4 8 x文件夹 但消息仍然存在
  • Rmd 文件中的 knit_child 正在打印不需要的输出

    我已经成功使用了knit child生成pdf文件 遵循以下代码http yihui name knitr demo child http yihui name knitr demo child 但是当我尝试在 Rmd file r res
  • 如何将复杂的 T-SQL 转换为 Linq

    我正在使用 EntityFramework Core 2 0 从事 Asp NET Core 2 0 项目 我正在尝试将现有的遗留 SQL 存储过程转换为 EntityFramework Core 中的 Linq 但我在处理 T SQL 的
  • 何时使用抽象语法树或具体语法树?

    我一直在研究编译器 词法分析器似乎非常简单 取一个 句子 并将其分解为单词 或标记 为了确保语法正确 需要解析器 解析器通常采用标记并构建一棵树 该树产生根节点 单词到句子 段落 页面等 From 这个问题 https stackoverf
  • 取消部分CSS样式

    对于一个项目 我必须使用定义的样式表 我无法编辑它 我必须接受它 但是 有些样式不适合该网站 例如边距 我也创建了自己的 CSS 文件来覆盖其中一些属性 举个例子 如果我有这个 div class container My test tex
  • 为什么这个将字符串转换为整数的 Golang 代码会失败?

    这应该很简单 strconv Atoi 1250000 0000 这会导致错误 0 strconv ParseInt 解析 1250000 0000 语法无效 有什么线索吗 Atoi仅适用于可以解析为整数的字符串 你需要的是解析浮点型 ht
  • 一台视频混合渲染器 9 (VMR9) 可以渲染更多视频流吗?

    我使用相同数量的 VMR9 实例以 Windows 形式渲染多个视频流 我使用 DirectShowLib 2005 在 C 中执行此操作 如果需要显示 100 个视频 我将创建 100 个 FilterGraph IFilterGraph
  • 在 WooCommerce 中随处保存并显示产品选择的自定义数据

    我有一个代码显示产品编辑页面上的复选框 当我单击此复选框时 单个产品页面上会显示一个选择框 这是我的代码 Display Checkbox Field add action woocommerce product options gener