【问题标题】:Custom field validation in Woocommerce single product pages [closed]Woocommerce 单个产品页面中的自定义字段验证 [关闭]
【发布时间】:2018-05-02 01:16:27
【问题描述】:

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

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

任何帮助将不胜感激, 我不知道从哪里开始。

【问题讨论】:

  • 致社区:这不太宽泛 ...抱歉

标签: php wordpress validation woocommerce product


【解决方案1】:

这可以通过 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 文件中。经过测试并且可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多