我想创建一个带有附加文本输入字段的Woocommerce产品,该字段检查输入的值是否对该字段是唯一的,否则输出消息。
换句话说,如果我输入“dave”并且“dave”已由其他用户提交,那么我就无法继续购买。
非常感谢任何帮助, 我不知道从哪里开始。
答案 0 :(得分:2)
这可以通过非常简单的方式以3个小钩子函数完成:
将为当前产品验证提交的值...
代码:
// The product custom field before add-to-cart button - Frontend
add_action( 'woocommerce_before_add_to_cart_button', 'action_before_add_to_cart_button' );
function action_before_add_to_cart_button() {
global $product;
echo '<div>';
woocommerce_form_field( 'custom_unique', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('The label name'),
'placeholder' =>__('Please enter …'),
'required' => true,
), '' );
// For test: displaying existing submitted values (commented - inactive)
// print_r( get_post_meta( $product->get_id(), '_custom_unique_values', true ) );
echo '</div><br>';
}
// Field validation (Checking)
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 20, 3 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity ) {
// Get the custom field values to check
$custom_unic_values = (array) get_post_meta( $product_id, '_custom_unique_values', true );
// Check that the value is unique
if( in_array( $_POST['custom_unique'], $custom_unic_values ) ){
$passed = false ; // Set as false when the value exist
// Displaying a custom message
$message = sprintf( __( 'The value "%s" already exist, try something else…', 'woocommerce' ), sanitize_text_field( $_POST['custom_unique'] ) );
wc_add_notice( $message, 'error' );
}
return $passed;
}
// Save the new unique value in the array of values (as product meta data)
add_action( 'woocommerce_add_to_cart', 'action_add_to_cart', 20, 6 );
function action_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
if( isset($_POST['custom_unique']) ){
// Get the array of existing values
$custom_unic_values = (array) get_post_meta( $product_id, '_custom_unique_values', true );
// append the new value to the array of values
$custom_unic_values[] = sanitize_text_field( $_POST['custom_unique'] );
// Save the appended array
update_post_meta( $product_id, '_custom_unique_values', $custom_unic_values );
}
}
代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。