Woocommerce单一产品页面中的自定义字段验证

时间:2018-05-02 01:16:28

标签: php wordpress validation woocommerce product

我想创建一个带有附加文本输入字段的Woocommerce产品,该字段检查输入的值是否对该字段是唯一的,否则输出消息。

换句话说,如果我输入“dave”并且“dave”已由其他用户提交,那么我就无法继续购买。

非常感谢任何帮助, 我不知道从哪里开始。

1 个答案:

答案 0 :(得分:2)

这可以通过非常简单的方式以3个小钩子函数完成

  • 第一个,在单个产品页面中添加到购物车按钮之前添加自定义输入文本字段
  • 第二个进行验证,检查这是一个唯一值
  • 第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文件中。经过测试和工作。

enter image description here

相关问题