When using a custom settings tab in WooCommerce, like:
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);
}
How can I perform custom validation on the example_input field before allowing it to save to the database, and, if needed, throw an error to tell the user what’s wrong with the input?
2
Answers
You can make field required by just adding the html5 required attribute to the field.
But in you case if you want to display error message on field update you can do something like this. add filter
woocommerce_admin_settings_sanitize_option_<option_name>
Edit
You can loop through all options like this
I have tried to meet your requirement with simple filter option available in woo-commerce.
I have added only one more filter and basic login on that filter. Filter name is
woocommerce_admin_settings_sanitize_option
you need to apply your logic on this filter which will do everything as per your need.
you can prevent saving of the option if there is an error by setting empty value and then show notice for that field too.
I have aded one custom attributes to do validation and the name of the attribute is ‘custom_validate’
If there is an empty field then below attributes value prevent from storing data.
Put whole code snippet in your functions.php and start tracing the flow. Hope you will get it
}