根据 Woocommerce 中的选定值显示或隐藏注册字段

2023-11-29

我正在尝试为我的网站定制注册表单。我一直在使用本指南,并已成功为我的注册表单创建/存储其他字段。定制注册指南。

I have created a drop-down/select field in my registration form for the user to select whether they want a Standard or Education account-type when registering: enter image description here

如果他们选择教育帐户类型,我希望显示其他字段,以便我可以收集他们学校的其他数据。有没有办法让我根据表单中另一个字段的当前值提供条件逻辑来判断某个字段是否可见?

Here's kind of an example of what I would want to accomplish: enter image description here

有人可以指出我完成条件表单字段的正确方向吗?另外,我不想为此使用第三方插件。对此,拥有完全控制权非常重要。

编辑: 根据要求,这是我的函数的完整代码:

    <?php
/*
Plugin Name: Custom Account Fields
Plugin Author: Case Silva
*/

//Create Custom Fields
if(!function_exists('get_custom_fields')){
    function get_custom_fields(){
        return apply_filters('custom_fields', array(
            'verified_education_acct' => array(
                'type' => 'checkbox',
                'label' => __('Verified?'),
                'required' => false,
                'hide_in_account' => true,
                'hide_in_admin' => false,
                'hide_in_registration' => true,
                'hide_in_checkout' => true
            ),
            'customer_id_num' => array(
                'type' => 'text',
                'label' => __('Customer ID# '),
                'placeholder' => __('e.g. 1234567890'),
                'required' => false,
                'hide_in_account' => true,
                'hide_in_admin' => false,
                'hide_in_checkout' => true,
                'hide_in_registration' => true
            ),
            'account_type' => array(
                'type' => 'select',
                'label' => __('What type of account will this be?'),
                'options' => array(
                    '' => __('Select an option...'),
                    1 => __('Education'),
                    2 => __('Standard')
                ),
                'required' => true,
                'hide_in_account' => true,
                'hide_in_admin' => false,
                'hide_in_checkout' => false,
                'hide_in_registration' => false
            ),
            'school_name' => array(
                'type' => 'text',
                'label' => __('School Name'),
                'placeholder' => __('e.g. North Middle School'),
                'required' => true,
                'hide_in_account' => 'account_type' != 1,
                'hide_in_admin' => false,
                'hide_in_checkout' => 'account_type' != 1,
                'hide_in_registration' => 'account_type' != 1
            ),
        ));
    }
}

//Add them to User Area
if(!function_exists('print_user_frontend_fields')){
    function print_user_frontend_fields(){
        $fields = get_custom_fields();
        $user_logged_in = is_user_logged_in();

        foreach ($fields as $key => $field_args) {
            if($user_logged_in && !empty($field_args['hide_in_account'])){
                continue;
            }
            if(! $user_logged_in && ! empty($field_args['hide_in_registration'])){
                continue;
            }
            woocommerce_form_field($key, $field_args);
        }
    }
}

//Add them to Admin Area
if(!function_exists('print_user_admin_fields')){
    function print_user_admin_fields(){
        $fields = get_custom_fields();

        ?>
        <h2><?php _e('Education/School Information'); ?></h2>
        <table class = "form-table" id = "additional-information">
            <tbody>
                <?php foreach ($fields as $key => $field_args) { ?>
                    <?php
                    if(! empty($field_args['hide_in_admin'])){
                        continue;
                    }

                    $user_id = get_edit_user_id();
                    $value = st_get_userdata($user_id, $key);
                    ?>
                    <tr>
                        <th>
                            <label for="<?php echo $key; ?>"><?php echo $field_args['label']; ?></label>
                        </th>
                        <td>
                            <?php $field_args['label'] = false; ?>
                            <?php woocommerce_form_field($key, $field_args, $value); ?>
                        </td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
        <?php
    }
}

//Save them to the database
if(!function_exists('save_acct_fields')){
    function save_acct_fields($customer_id){
        $fields = get_custom_fields();
        $sanitized_data = array();

        foreach ($fields as $key => $field_args) {
            if(! is_field_visible($field_args)){
                continue;
            }

            $sanitize = isset($field_args['sanitize']) ? $field_args['sanitize'] : 'wc_clean';
            $value = isset($_POST[$key]) ? call_user_func($sanitize, $_POST[$key]) : '';

            if(is_userdata($key)){
                $sanitized_data[$key] = $value;
                continue;
            }

            update_user_meta($customer_id, $key, $value);
        }

        if(! empty($sanitized_data)){
            $sanitized_data['ID'] = $customer_id;
            wp_update_user($sanitized_data);
        }
    }
}

//Check if field is visible on page
if(!function_exists('is_field_visible')){
    function is_field_visible($field_args){
        $visible = true;
        $action = filter_input(INPUT_POST, action);

        if(is_admin() && ! empty($field_args['hide_in_admin'])){
            $visible = false;
        } elseif((is_account_page() || $action === 'save_account_details') && is_user_logged_in() && ! empty($field_args['hide_in_account'])){
            $visible = false;
        } elseif((is_account_page() || $action === 'save_account_details') && ! is_user_logged_in() && ! empty($field_args['hide_in_registration'])){
            $visible = false;
        } elseif(is_checkout() && ! empty($field_args['hide_in_checkout'])){
            $visible = false;
        }
        return $visible;
    }
}

//Check if field is predefined
if(!function_exists('is_userdata')){
    function is_userdata($key){
        $userdata = array(
            'user_pass',
            'user_login',
            'user_nicename',
            'user_url',
            'user_email',
            'display_name',
            'nickname',
            'first_name',
            'last_name',
            'description',
            'rich_editing',
            'user_registered',
            'role',
            'jabber',
            'aim',
            'yim',
            'show_admin_bar_front'
        );
        return in_array($key, $userdata);
    }
}

//Populate form with submitted data
if(!function_exists('get_edit_user_id')){
    function get_edit_user_id(){
        return isset($_GET['user_id']) ? (int) $_GET['user_id'] : get_current_user_id();
    }
}

//Access saved data
if(!function_exists('st_get_userdata')){
    function st_get_userdata($user_id, $key){
        if(!is_userdata($key)){
            return get_user_meta($user_id, $key, true);         
        }

        $userdata = get_userdata($user_id);

        if(!$userdata || ! isset($userdata->{$key})){
            return '';
        }

        return $userdata->{$key};
    }
}

add_action('woocommerce_register_form', 'print_user_frontend_fields', 10);
add_action('woocommerce_edit_account_form', 'print_user_frontend_fields', 10);

add_action('show_user_profile', 'print_user_admin_fields', 30);
add_action('edit_user_profile', 'print_user_admin_fields', 30);

add_action('woocommerce_created_customer', 'save_acct_fields');
add_action('personal_options_update', 'save_acct_fields');
add_action('edit_user_profile_update', 'save_acct_fields');
add_action('woocommerce_save_account_details', 'save_acct_fields');
?>

显示隐藏字段的唯一方法是使用 Javascript/jQuery,因为它是客户端的事件。

所以我对您的代码做了一些小更改,添加了必要的 jQuery 来处理显示和隐藏school_name文本字段取决于account_type选择现场直播活动选择。

以下是我在您的代码中更改的两个函数:

// Get custom fields
if(!function_exists('get_custom_fields')){
    function get_custom_fields(){
        return apply_filters('custom_fields', array(
            'verified_education_acct' => array(
                'type' => 'checkbox',
                'label' => __('Verified?'),
                'required' => false,
                'hide_in_account' => true,
                'hide_in_admin' => false,
                'hide_in_registration' => true,
                'hide_in_checkout' => true
            ),
            'customer_id_num' => array(
                'type' => 'text',
                'label' => __('Customer ID# (Acumatica)'),
                'placeholder' => __('e.g. 1234567890'),
                'required' => false,
                'hide_in_account' => true,
                'hide_in_admin' => false,
                'hide_in_checkout' => true,
                'hide_in_registration' => true
            ),
            'account_type' => array(
                'type' => 'select',
                'label' => __('What type of account will this be?'),
                'class' => array('form-row-wide'),
                'options' => array(
                    '' => __('Select an option...'),
                    1 => __('Education'),
                    2 => __('Standard')
                ),
                'required' => true,
                'hide_in_account' => true,
                'hide_in_admin' => false,
                'hide_in_checkout' => false,
                'hide_in_registration' => false,
                'js_trigger' => true, // <===  <=== Enabling Javascript 
            ),
            'school_name' => array(
                'type' => 'text',
                'label' => __('School Name'),
                'class' => array('form-row-wide off'), // <===  <===  Hidden field
                'placeholder' => __('e.g. North Middle School'),
                'required' => true,
                'hide_in_account' => false,
                'hide_in_admin' => false,
                'hide_in_checkout' => false,
                'hide_in_registration' => false,
                'js_triggered_by' => 'account_type', // <===  JS: field that trigger show/hide
                'js_show_val' => '1', // <===  <=== JS: selected field value that show this field 
            ),
        ));
    }
}

//Add them to User Area
if(!function_exists('print_user_frontend_fields')){
    function print_user_frontend_fields(){
        $fields = get_custom_fields();
        $user_logged_in = is_user_logged_in();
        $enable_js = false; // Initializing
        $data_js = []; // Initializing

        // Hiding conditional field (with "off" class)
        echo '<style>p.form-row.off{display:none;}</style>';

        foreach ($fields as $key => $field_args) {
            if($user_logged_in && !empty($field_args['hide_in_account'])){
                continue;
            }
            if(! $user_logged_in && ! empty($field_args['hide_in_registration'])){
                continue;
            }
            if( isset($field_args['js_trigger']) && $field_args['js_trigger'] ){
                $enable_js = true;
            }
            if( isset($field_args['js_triggered_by']) && $field_args['js_show_val'] ){
                $data_js[$key] = [ $field_args['js_triggered_by'] => $field_args['js_show_val'] ];
            }
            // Form fields output
            woocommerce_form_field($key, $field_args);
        }
        if( $user_logged_in || ! $enable_js ) return; // Exit

        // JQuery code
        ?>
        <script type="text/javascript">
        jQuery( function($){
            var a = <?php echo json_encode($data_js) ?>;
            $.each(a, function(b,o){
                $.each(o, function(k,v){
                    $('#'+k).on('change', function(){
                        var cf = '#'+b+'_field';
                        if ( $(this).val() == v && $(cf).hasClass('off') ) {
                            $(cf).removeClass('off');
                        } else if ( $(this).val() != v && ! $(cf).hasClass('off') ) {
                            $(cf).addClass('off');
                        }
                    });
                });
            });
        });
        </script>
        <?php
    }
}

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

1) 加载时,字段被隐藏。

enter image description here

2)选择“教育”,该字段已显示.

enter image description here

3)选择“标准”(或无), 该字段被隐藏.

enter image description here

要处理多个字段,您需要进行一些更改,因为此示例适用于一个字段。

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

根据 Woocommerce 中的选定值显示或隐藏注册字段 的相关文章

  • 解析“流”JSON

    我在浏览器中有一个网格 我想通过 JSON 将数据行发送到网格 但浏览器应该在接收到 JSON 时不断解析它 并在解析时将行添加到网格中 换句话说 在接收到整个 JSON 对象后 不应将行全部添加到网格中 应该在接收到行时将其添加到网格中
  • 使用模数按字母顺序对列表进行排序

    我在获取元素列表并按字母顺序对它们进行排序方面没有任何问题 但我很难理解如何使用模数来做到这一点 更新 这是按我的方式工作的代码 但是 我更喜欢下面提供的答案的可重用性 因此接受了该答案
  • PNG 透明度问题 - 带有黑色阴影的褪色图像 - IE 中的边框

    我使用图像旋转器在主页上显示一些图像 所有图像均为 PNG 格式 问题出在 IE 7 8 中 图像旁边有黑色阴影 我花了几个小时来解决这个问题 但仍然不知道问题出在哪里以及如何删除它 没有人有类似的问题和提示吗 如何解决 尝试使用 img
  • 我想检查 $('#td1').text() === "x" 是否?

    我想检查innerHtml是否有X或O 所以我不能再次添加任何其他东西 但它不起作用 添加检查代码后它就停止了 我在这里尝试做一个简单的XO游戏来更熟悉javascript和jquery 我也不确定是否可以用 jQuery 做到这一点
  • 使用 jQuery/JS 打开时使
    标签的内容具有动画效果

    我只想要 HTML5 的内容details标记为 滑行 动画打开 而不是仅仅弹出打开 立即出现 这可以用 jQuery Javascript 实现吗 Fiddle http jsfiddle net 9h4Hq HTML
  • jquery.validate 中是否有一个函数可以像重置表单一样重置单个字段?

    我想调用 jquery 函数来手动删除单个字段中的错误并重置错误标记 是否有一个函数可以执行此操作 类似于 resetForm 函数 您可以执行以下操作来验证单个字段 your field valid 也许它会对某人有所帮助 Thanks
  • Woocommerce 结账自定义选择字段

    我有以下功能 将选择列表添加到 woo commerce 结账表单中 woocommerce form field airport pickup array type gt select class gt array airport pic
  • Jquery/Javascript 上传和下载文件,无需后端

    是否可以在没有后端服务器的情况下在 JavaScript 函数中下载和上传文件 我需要导出和导入由 JavaScript 函数生成的 XML 我想创建按钮 保存 xml 来保存文件 但我不知道是否可行 另一方面 我希望将 XML 文件直接上
  • 使用 Ajax.Request 将 JSON 从浏览器传递到 PHP 的最佳方法

    您好 我有一个 JSON 对象 它是一个二维数组 我需要使用 Ajax Request 将其传递给 PHP 我知道的唯一方法 现在我使用js函数手动序列化我的数组 并获取以下格式的数据 s 1 d 3 4等 我的问题是 有没有办法更直接 有
  • 将div设置为隐藏,延时后可见

    我试图在 X 时间后 也许甚至在随机时间之后 但现在我们只做固定时间 在黑色背景上出现一个黄色方块 function initialSetup if document getElementById yellow null document
  • php 错误 fopen(): 文件名不能为空

    发送带有附件代码的电子邮件工作正常 最近我们已将文件传输到另一个托管服务器 idk 发生了什么 它显示以下错误 警告 fopen 第 106 行 home hugerecruitmetnt public html validatecva p
  • Doctrine EntityManager 清除嵌套实体中的方法

    我想用学说批量插入处理 http doctrine orm readthedocs org en latest reference batch processing html为了优化大量实体的插入 问题出在 Clear 方法上 它表示此方法
  • 如何使用 JQuery 动态排序

    如果我有一个下拉列表和一个列表框 有没有办法使用 JQuery 根据下拉列表对列表框进行排序 举个例子会很有帮助 这会改变下拉菜单中的顺序 您必须根据自己的标准设置顺序
  • 如何更改此 jquery 插件的时区/时间戳?

    我正在使用这个名为 timeago 的插件 在这里找到 timeago yarp com 它工作得很好 只是它在似乎不同的时区运行 我住在美国东部 费城时区 当我将准确的 EST 时间放入 timeago 插件时 比如 2011 05 28
  • 如何在 Laravel 中使用 PUT http 动词提交表单

    我知道这个问题可能已经提出 但我就是无法让它发挥作用 如果有人可以帮助我 我将非常感激 我安装了 colletive form 但答案也可以是 html 表单标签 现在列出我的表格 我的路线和我的例外情况 Form model array
  • 如何使用 PHPExcel 库从 Excel 获取日期

    我正在尝试使用 PHPExcel 从 Excel 获取日期 但我没有得到日期 我得到的字符串值不是 1970 以来的秒数 我尝试过的代码是 InvDate trim excel gt getActiveSheet gt getCell B
  • post php mysql 的拆分关键字

    我有一个表存储帖子 ID 它的标签如下 Post id Tags 1 keyword1 keyword2 keyword3 我想循环遍历该表中的每一行并执行以下操作 将关键字1 关键字2 关键字3放入新表中 word id word val
  • Javascript/Jquery:确定用户是否使用鼠标滚轮、滚动条或键盘滚动

    我正在尝试让用户界面正常工作 如果他们使用鼠标滚轮 我需要让它以一种方式滚动 如果他们使用滚动条 我需要让它以另一种方式滚动 如果他们使用键盘 我需要让它以另一种方式滚动 我相信滚轮和滚动条都充当鼠标事件 但是当单击滚动条时我无法让 jav
  • Spring Rest 和 Jsonp

    我正在尝试让我的 Spring Rest 控制器返回jsonp但我没有快乐 如果我想返回 json 但我有返回的要求 完全相同的代码可以正常工作jsonp我添加了一个转换器 我在网上找到了用于执行 jsonp 转换的源代码 我正在使用 Sp
  • fullCalendar 未显示正确的结束日期

    我正在看调试页面 http jsbin com wukofacaxu edit js outputFullCalendar 官方网站的 我想安排一个活动时间为 22 09 2015 至 30 09 2015 dd mm yyyy 但它只显示

随机推荐

  • 用于文本选择控件的自定义浮动工具栏

    我想自定义选择文本时出现的浮动工具栏 这是标准浮动工具栏的示例 你知道我如何定制它 比如添加粗体 斜体 吗 有外部图书馆吗 Monospace 应用程序正是我想要的 您将向清单中的活动添加一个意图过滤器
  • Flask Postgresql 数组不会永久更新

    我正在开发一个使用 Flask 和 PostgreSQL 数据库以及 SQLAlchemy 的项目 I have Group具有以下列表的对象User属于该组成员的 ID 由于某种原因 当我尝试将 ID 添加到组时 它无法正确保存 如果我尝
  • 谷歌折线图 X 轴上有双标签

    我正在研究谷歌折线图 我想在 x 轴上加双标签 日期明智的过程 我可以使用下面的代码绘制没有日期的图表 但无法填充日期 div style width 100 height 1 div
  • 错误:getaddrinfo ENOTFOUNDregistry.npmjs.orgregistry.npmjs.org:443

    我正在公司网络上工作 正在尝试安装npm 但我一次又一次地收到此错误 npm install npm ERR Windows NT 6 1 7601 npm ERR argv C Program Files nodejs node exe
  • 在 Swift 中声明自引用指针[重复]

    这个问题在这里已经有答案了 这段 Obj C 代码在 swift 中的等价物是什么 我猜测 CMutableVoidPointer 的一些事情 static void CapturingStillImageContext Capturing
  • Nhibernate 通过用户定义的函数输出进行过滤

    我对 NHibernate 相当陌生 到目前为止一切都进展顺利 但我遇到了一个问题 我不太确定如何解决 基本上我需要按用户定义函数的输出进行过滤 如果我用 SQL 编写 我会这样写 declare Latitude decimal decl
  • Coldfusion 8 同时执行 CFIf 和 CFElse 语句

    我正在为电子商务网站制作用户注册应用程序 但我遇到了一个非常奇怪的问题 当我运行这段代码时
  • C++ 中的临时对象确实是 const 吗?

    我一直认为C 中的临时对象会被编译器自动视为const 但最近我经历了以下代码示例 function returning object some non const method 对 C 编译器有效 这让我想知道 C 中的临时对象确实是 c
  • PHP 匿名函数:未定义的变量

    我有这两个 WordPress 功能 wpb set post views function postID count key wpb post views count count get post meta postID count ke
  • Codeigniter 与本地主机 (XAMPP) 中的路径有关的问题

    无论如何 我的代码点火器安装中的索引页面 又名 homepage php 都工作正常 The problem lies with using subdirectories to store other pages currently its
  • android 中网页视图内容闪烁?

    我在用着this用于水平滑动的 lib 检查下面的代码 滑动功能工作正常 但当我直接滑动时 不会在网页视图上显示内容 显示下面的一些图片以了解更多详细信息 在上图之后 当我滑动时 它效果很好 但是当我们想直接进入下一张幻灯片时 就会面临如下
  • 始终显示 AVPlayer 控件

    我有一个 AVPlayerViewController 里面有一个 AVPlayer 我需要的是播放器的控件 播放 暂停 时间滑块 永远不会隐藏 现在 在播放视频大约 4 秒后 它们就会隐藏起来 您必须点击屏幕才能再次显示它们 我无法找到解
  • 当menuItem中使用shiny和shinydashboard的更多功能时,tabItem无法显示内容

    我正在学习闪亮和闪亮的仪表板 我的代码是这样的 library shiny library shinydashboard library DT library RODBC library stringr library dplyr ch l
  • 如何在 Yesod 应用程序中的 GHCi 中执行数据库查询

    例如 如何使用 Yesod 应用程序的模型将新用户插入数据库 或者 还有更好的方法 我正在处理脚手架应用程序 现在我创建了App实例 但不知道如何使用它执行请求 i Extra data Extra Extra extraCopyright
  • 如何将svg中的一条路径分成两条路径

    我对 svg 语法非常陌生 我想知道如何将一条路径分成两条路径 实际上我有这样的东西 M Xm Ym C Xc1 Yc1 Xc2 Yc2 Xc3 Yc3 C Xd1 Yd1 Xd2 Yd2 Xd3 Yd3 C 是我要分割路径的地方 我想将其
  • Oozie 与 Hadoop 2,作业挂在“RUNNING”状态

    我有一个带有 java 操作节点的工作流程作业 使用 Hadoop 2 1 0 2 0 4 0 38 和 Oozie 3 3 2 2 0 4 0 运行 当我提交作业时 我在 Hadoop 资源管理器屏幕中看到 2 行 1 原职位名称 2 使
  • C++内存模型是否提供有关构造函数操作的保证[关闭]

    Closed 这个问题需要多问focused 目前不接受答案 如何确保新构造的不可变对象可以在 C 线程之间安全共享 C 内存模型是否为构造函数的操作提供保证 当多个线程共享对某个对象的访问并且该对象被修改时 可能会出现竞争危险 这些问题可
  • IIS WCF 服务托管与 Windows 服务

    我们开发了一个 WCF 服务 并希望部署它 我们的客户将使用它basicHttpBinding但我们的内部团队将使用它namedPipesBinding 我们想知道将其托管在 IIS 7 中或使用 Windows 服务是否更好 我们运行了一
  • 无法安装 numpy - 需要 MS Visual C++ 14.1。但是已经安装了

    我在 Windows 10 上使用 pypy3 6 v7 3 0 我正在尝试安装 numpypip install numpy 但我不断收到错误 error Microsoft Visual C 14 1 is required Get i
  • 根据 Woocommerce 中的选定值显示或隐藏注册字段

    我正在尝试为我的网站定制注册表单 我一直在使用本指南 并已成功为我的注册表单创建 存储其他字段 定制注册指南 I have created a drop down select field in my registration form f