gpt4 book ai didi

php - WooCommerce 自定义设置选项卡验证

转载 作者:行者123 更新时间:2023-12-04 17:31:21 29 4
gpt4 key购买 nike

在 WooCommerce 中使用自定义设置选项卡时,例如:

add_filter('woocommerce_settings_tabs_array', 'add_my_custom_tab', 50);

function add_my_custom_tab($settings_tabs) {
$settings_tabs['my_custom_tab'] = __('My Custom Tab', 'my-custom-tab');
return $settings_tabs;
}

add_action('woocommerce_settings_tabs_my_custom_tab', 'my_custom_tab');

function my_custom_tab() {
woocommerce_admin_fields(get_custom_settings());
}

add_action('woocommerce_update_options_my_custom_tab', 'update_my_custom_tab_settings');

function update_my_custom_tab_settings() {
woocommerce_update_options(get_custom_settings());
}

function get_custom_settings() {
$settings = array(
'section_title' => array(
'name' => __('Custom Options', 'woocommerce-my-custom-tab'),
'type' => 'title',
'desc' => '',
'id' => 'wc_custom_tab'
),
'example_input' => array(
'name' => __('My Input', 'woocommerce-my-custom-tab'),
'type' => 'text',
'desc' => '',
'id' => 'wc_my_input'
),
'section_end' => array(
'type' => 'sectionend',
'id' => 'wc_section_end'
)
);
return apply_filters('wc_my_custom_tab_settings', $settings);
}

如何在将 example_input 字段保存到数据库之前对其执行自定义验证,并在需要时抛出错误以告知用户输入有什么问题?

最佳答案

您只需将 html5 所需属性添加到字段即可使字段成为必填字段。

'example_input' => array(
'name' => __('My Input', 'woocommerce-my-custom-tab'),
'type' => 'text',
'desc' => '',
'custom_attributes' => array( 'required' => 'required' )
'id' => 'wc_my_input'
),

但是在你的情况下,如果你想在字段更新时显示错误消息,你可以这样做。添加过滤器 woocommerce_admin_settings_sanitize_option_<option_name>

// define the woocommerce_admin_settings_sanitize_option_<option_name> callback 
function filter_woocommerce_admin_settings_sanitize_option_wc_my_input( $value, $option, $raw_value ) {
add_action( 'admin_notices', function() use($value) {
if($value == ""){
echo '<div id="message" class="notice notice-error is-dismissible"><p>Option is required</p></div>';
}
});
return $value;
};
// add the filter
add_filter( "woocommerce_admin_settings_sanitize_option_wc_my_input", 'filter_woocommerce_admin_settings_sanitize_option_wc_my_input', 10, 3 );

编辑

你可以像这样遍历所有选项

$options = ['wc_my_input' => 'My Input', 'other_field' => 'Other Field']; // get all the options here
foreach($options as $option_name => $option_val){
// define the woocommerce_admin_settings_sanitize_option_$option_name callback
add_filter( "woocommerce_admin_settings_sanitize_option_$option_name", function($value, $option, $raw_value) use($option_val) {
add_action( 'admin_notices', function() use($value) {
if($value == ""){
echo "<div id=\"message\" class=\"notice notice-error is-dismissible\"><p>$option_val is required</p></div>";
}
});
return $value;
}, 10, 3 );
}

关于php - WooCommerce 自定义设置选项卡验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59370947/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com