Woocommerce 产品自定义字段:检查输入是否已存在

2023-12-02

我安装了这个“WC Fields Factory”插件来向产品添加新字段,但我需要检查这个新文本框的值是否已存在于数据库中。 举个例子,比如在注册时您不能使用已在使用的电子邮件。

我必须像屏幕上一样添加文本字段

enter image description here


Update 2 - 处理字段验证,仅允许唯一的不存在的文本输入

以下是在单个产品页面中添加自定义文本字段、将其添加为购物车项目数据、在购物车和结账页面中显示、将其另存为订单项目数据以及在订单和电子邮件通知中显示的完整方法:

// HERE define your field label name
function get_field_label_name(){
    return __( "The label name" );
}


// Add a custom product note below product meta in single product pages
add_action('woocommerce_before_add_to_cart_button', 'my_product_custom_field', 100 );
function my_product_custom_field() {

    echo '<div class="my-custom-field">';

    woocommerce_form_field('custom_field1', array(
        'type'        => 'text',
        'class'       => array( 'my-field-class form-row-wide') ,
        'label'       => get_field_label_name(),
        'placeholder' => __("The field placeholder…" ),
        'required'    => true, // Or false
    ) , '');

    echo '</div>';
}

// Check if the custom field value is unique
add_filter( 'woocommerce_add_to_cart_validation', 'wc_add_on_feature', 20, 3 );
function wc_add_on_feature( $passed, $product_id, $quantity ) {
    if( isset($_POST['custom_field1']) && ! empty($_POST['custom_field1']) ){
        global $wpdb;

        $label = get_field_label_name();
        $value = sanitize_text_field( $_POST['custom_field1'] );

        // Check if value exits already
        $result = $wpdb->get_var( "
            SELECT COUNT(meta_value) FROM {$wpdb->prefix}woocommerce_order_itemmeta
            WHERE meta_key LIKE '$label' AND meta_value LIKE '$value'
        " );

        // If it exist we don't allow add to cart
        if( $result > 0 ){
            // Display an error notice
            wc_add_notice( sprintf( __( 'This "%s" input already exist. Please choose another one…' ), $value ), 'error' );
            $passed = false;
        }
    }
    return $passed;
}

// Add custom field value to cart item data
add_filter( 'woocommerce_add_cart_item_data', 'custom_field_value_to_cart_item_data', 20, 2 );
function custom_field_value_to_cart_item_data( $cart_item_data, $product_id ){
    if( isset($_POST['custom_field1']) && ! empty($_POST['custom_field1']) ){
        $cart_item_data['custom_data'] = sanitize_textarea_field( $_POST['custom_field1'] );
    }
    return $cart_item_data;
}


// 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 ) {

    if ( isset( $cart_item['custom_data'] ) ){
        $cart_item_data[] = array(
            'name' => get_field_label_name(),
            'value' =>  $cart_item['custom_data']
        );
    }
    return $cart_item_data;
}

// Save and display custom field in orders and email notifications (everywhere)
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['custom_data'] ) ){
        $item->update_meta_data( get_field_label_name(),  $values['custom_data'] );
    }
}

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

enter image description here

enter image description here

enter image description here

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

Woocommerce 产品自定义字段:检查输入是否已存在 的相关文章

随机推荐

  • 为什么“TYPE*​​ const”指针有不同的行为?

    下面的代码正在处理一个TYPE const指针 struct D void Check D const p new D 2nd test is p 0 cout lt lt p lt
  • iOS 5 Segue 在第一次执行后不工作

    我正在使用情节提要功能创建一个 iOS5 应用程序 基本结构是 LoginScreen segue gt MyScreen 按注销 segue 返回登录屏幕 gt LoginScreen 这很简单 我管理第一个segue的方式是 void
  • 如何列出詹金斯管道作业中的所有“env”属性?

    给定一个詹金斯构建管道 詹金斯注入一个变量env进入node 多变的env保存环境变量和值 我要打印all env詹金斯管道内的属性 然而 我不知道all env提前属性 例如环境变量BRANCH NAME可以用代码打印 node echo
  • 如何在 Visual Studio C++ 中使用第三方 DLL 文件?

    我知道我需要使用 LoadLibrary 但是 为了使用第三方 DLL 文件 我还需要采取哪些其他步骤呢 我只是跳进了 C 这是我 作为 Java 程序员 唯一没有得到的部分 我只是在研究如何使用Qt库和 tesseract ocr 但这个
  • laravel 4 分页集合

    我无法使用 laravel 4 创建正确的分页系统 我有以下返回集合的模型和函数 示范餐厅 public function fooditem return this gt hasMany Fooditem rest id public fu
  • python 中的位移位

    我想理解下面的代码 第三条线正在做什么转变 number 1 265 bits 8 shifted no 1 265 2 bits 如果我检查 number 和shifted no 结果的二进制格式 0011 1111 1010 0001
  • 如何让新的小部件填充可用空间?

    我在让新的 QT 小部件填充所有可用空间时遇到一些麻烦 我想将一个小部件 QGLWidget 添加到垂直布局 mVisual 并调整布局大小 以便 mVisual 占据最大面积 我的布局如下所示 我的代码是 ui setupUi this
  • 输入键模拟单击对复选框不起作用

    我复制并稍微修改了底部的代码这个帖子允许在我创建的工作表表单上的表单控件之间进行 Tab 键切换 以下是与 KeyCode vbKeyEnter 相关的部分 Select Case KeyCode Case vbKeyTab Dim Bac
  • Delphi网络摄像头简单程序

    任何人都可以帮助我使用 delphi 中的一个简单的 TVideo 组件创建一个简单的 cam 视图 视频大小默认为 160x120 不调整大小 只是一个简单的 请 我的新项目急需 thanks 有很多方法可以做到这一点 我无法理解 TVi
  • numpy where 函数的基础知识,它对数组有什么作用?

    我看过帖子了nonzero a where a 和 argwhere a 之间的差异 什么时候用哪个 我不太明白 numpy 模块中 where 函数的用法 例如我有这个代码 import numpy as np Z np array 1
  • 如何增加 Torque 作业的 OpenFabrics 内存限制?

    当我通过 InfiniBand 运行 MPI 作业时 出现以下磨损情况 我们使用扭矩管理器 WARNING It appears that your OpenFabrics subsystem is configured to only a
  • 使用 C++ 的原理与实践中头文件中的错误消息

    我刚刚开始使用 编程 使用 C 的原理和实践 学习 C 那本书告诉我使用一个头文件来为我设置一些东西 有问题的头文件位于http www stroustrup com Programming std lib facilities h 我正在
  • WPF 中的用户控件位置

    我是 WPF 新手 我创建了一个新的 UserControl MyUserControl 现在我很惊讶 UserContol 没有位置 我如何读取 通过代码 myUserControl1 Location在父容器中 我解释 我有一些点 用户
  • Docusign 代表发送 (SOBO)

    如果有人有 我欢迎提供有关如何使用 Docusign 的代表发送 SOBO 功能的示例 我正在使用带有 XML 的 SOAP API 甚至 Docusign 的 III 级支持也无法提供示例 Thanks 2021 年 4 月更新 新的 R
  • java.rmi.ConnectException:连接拒绝主机:127.0.1.1;

    java rmi ConnectException Connection refused to host 127 0 1 1 nested exception is java net ConnectException Connection
  • 如何将 JPA 字段持久化为 clob?

    我有一个类不能很好地序列化为关系实体 因此 我想使用 JPA 作为 CLOB 来持久化它 我可以将它序列化为字符串 我该如何使用 JPA 来做到这一点 示例实体 Entity Table name MY TABLE public class
  • 如何使用 const getter 对 std::set 进行排序

    我有一个 std set 容器 其元素是以下类的对象 class LaneConnector public const Lane getLaneFrom const return From const Lane getLaneTo cons
  • 上午 12 点和下午 12 点的时间正则表达式

    我做了这个正则表达式 00 0 0 9 1 012 0 5 0 9 a p m A P M 但问题是它正在接受 00 00 am 我不想这样 如何忽略 我希望时间采用这种格式 上午 12 12 它不应该在这个 上午 00 21 我正在使用此
  • Spring Boot 触发完全重启,而不是在静态文件发生更改时重新加载

    In my Spring Boot项目我有以下结构 src main java resources static css js img webapp WEB INF views 根据文档排除资源 里面的资源static 应该触发一个relo
  • Woocommerce 产品自定义字段:检查输入是否已存在

    我安装了这个 WC Fields Factory 插件来向产品添加新字段 但我需要检查这个新文本框的值是否已存在于数据库中 举个例子 比如在注册时您不能使用已在使用的电子邮件 我必须像屏幕上一样添加文本字段 Update 2 处理字段验证