我使用 WooCommerce 插件 HUSKY 产品过滤器(以前称为 WOOF)有简单的过滤表单,客户选择产品类别,然后选择产品标签,然后可以在“按文本搜索”字段中写入产品编号。
我需要将此文本字段设为必填/强制,这样如果客户不在该字段中放置任何内容,提交按钮将不会过滤结果。
我在我的functions.php文件中使用了该代码作为子主题,但它不起作用,可能我使用了错误的字段名称表单插件。
add_filter( 'woof_fs_by_text', 'require_search_by_text_woof');
function require_search_by_text_woof( $fields ) {
$fields['woof_txt_search66e01ba5d1c01']['required'] = true;
return $fields;
}
包含公式的页面是:https://gres.info.pl/testowaa/
如果有人可以帮助我修复代码或使用其他方法使此字段成为必填字段,我将非常感激。
要使用 HUSKY 产品过滤器 (WOOF) 在 WooCommerce 过滤表单中强制输入搜索字段,如果搜索字段为空,您可能需要使用 JavaScript 来阻止表单提交,因为像 woof_fs_by_text 这样的 WordPress 过滤器可能无法提供您所需要的功能在这种情况下想要。
这是一种使用 JavaScript 来确保提交表单之前文本字段不留空的方法:
1 - 在您的
functions.php
中,将自定义 JavaScript 文件排入队列,如下所示:
function enqueue_custom_script() {
wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/custom-script.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_script');
2 - 使用以下 JavaScript 在您的子主题目录 (/wp-content/themes/your-child-theme/) 中创建一个名为
custom-script.js
的文件:
jQuery(document).ready(function($) {
// Listen for the form submission
$('form').on('submit', function(e) {
var searchText = $('#gres_search_text').val();
if (searchText.trim() === '') {
e.preventDefault();
alert('Please enter a product number in the search field before filtering.');
}
});
});
此方法直接检查文本字段是否已填充,如果未填充,则阻止使用 JavaScript 提交表单。