You need to enable JavaScript to run this app. WooCommerce单产品页面自定义字段唯一性验证技术求助
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce单产品页面自定义字段唯一性验证技术求助

How to Add a Unique Validation Custom Field to WooCommerce Products

Hey Dan, great question! Adding a unique custom field to WooCommerce products with duplicate-check validation is totally achievable. Let’s walk through the implementation step by step—no fancy plugins required, just some custom code you can drop into your site.

Step 1: Add the Custom Input Field to Product Pages

First, we need to render the text field on your product single page, right above the "Add to Cart" button. Use this code snippet:

add_action('woocommerce_before_add_to_cart_button', 'add_unique_custom_field_to_product');
function add_unique_custom_field_to_product() {
    echo '<div class="unique-field-wrapper">';
    echo '<label for="unique_product_code">' . __('Unique Code', 'woocommerce') . '<span class="required">*</span></label>';
    echo '<input type="text" id="unique_product_code" name="unique_product_code" required placeholder="' . __('Enter your unique code', 'woocommerce') . '">';
    echo '</div>';
}

This adds a required text field with a label and placeholder. You can tweak the label, placeholder, and styling by modifying the HTML here.

Step 2: Validate the Field for Uniqueness

Next, we need to check if the submitted value already exists in any completed/processing orders. We’ll hook into the WooCommerce add-to-cart validation to block duplicates:

add_filter('woocommerce_add_to_cart_validation', 'validate_unique_custom_field', 10, 3);
function validate_unique_custom_field($passed, $product_id, $quantity) {
    // Check if the field is submitted
    if (isset($_POST['unique_product_code']) && !empty($_POST['unique_product_code'])) {
        $submitted_code = sanitize_text_field($_POST['unique_product_code']);
        
        // Query orders to find existing instances of this code
        $existing_orders = wc_get_orders(array(
            'meta_key' => '_unique_product_code',
            'meta_value' => $submitted_code,
            'meta_compare' => '=',
            'status' => array('processing', 'completed'), // Exclude cancelled/refunded orders
            'limit' => 1, // Stop searching after finding one match
        ));
        
        // If a matching order exists, block add-to-cart and show error
        if (!empty($existing_orders)) {
            wc_add_notice(__('This code has already been used. Please enter a unique code.', 'woocommerce'), 'error');
            $passed = false;
        }
    } else {
        // Show error if field is empty
        wc_add_notice(__('Please enter a unique code.', 'woocommerce'), 'error');
        $passed = false;
    }
    
    return $passed;
}

Key notes here:

  • We use wc_get_orders to efficiently search for orders with the submitted code.
  • We only check active orders (processing/completed) to avoid counting cancelled or refunded ones—adjust the status array if you need different logic.
  • We sanitize the input to prevent malicious content.

Step 3: Save the Unique Field Value to Orders

Once validation passes, we need to save the code to the order so we can check it later. Use this snippet to store it as order item meta:

add_action('woocommerce_checkout_create_order_line_item', 'save_unique_field_to_order_item', 10, 4);
function save_unique_field_to_order_item($item, $cart_item_key, $values, $order) {
    if (isset($values['unique_product_code'])) {
        $item->add_meta_data('_unique_product_code', sanitize_text_field($values['unique_product_code']), true);
        // Also save it to the cart item temporarily so it persists to checkout
        wc_add_order_item_meta($item->get_id(), '_unique_product_code', sanitize_text_field($values['unique_product_code']));
    }
}

// Optional: Show the unique code on the order details page (for admin and customer)
add_action('woocommerce_order_item_meta_end', 'display_unique_field_on_order', 10, 4);
function display_unique_field_on_order($item_id, $item, $order, $plain_text) {
    $unique_code = $item->get_meta('_unique_product_code');
    if (!empty($unique_code)) {
        echo '<br><strong>' . __('Unique Code:', 'woocommerce') . '</strong> ' . esc_html($unique_code);
    }
}

This saves the code to the order item and displays it on the order confirmation page, My Account > Orders, and the admin order edit screen.

Step 4: Where to Put This Code

You have two solid options:

  • Child Theme’s functions.php: Add all the code snippets to your child theme’s functions.php file. This keeps the code safe when you update your parent theme.
  • Custom Plugin: Create a simple custom plugin (just a PHP file with a plugin header) and paste the code there. This is even better if you switch themes often.

Testing the Feature

After adding the code:

  1. Go to your product page, enter a code, and add the product to cart.
  2. Complete the checkout process.
  3. Try adding the same product again with the same code—you should see the error message and be blocked from adding it to cart.

If you need to adjust things like case sensitivity (e.g., treat "ABC" and "abc" as duplicates), just modify the $submitted_code line to strtolower(sanitize_text_field($_POST['unique_product_code'])) and update the meta value in the order save function to lowercase too.

内容的提问来源于stack exchange,提问作者Dan W

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:12:47