添加产品时,如何在woocommerce产品页面中制作自定义字段值(必填)

时间:2014-05-23 05:16:42

标签: php wordpress woocommerce custom-fields required

我在woocommerce的添加产品页面中添加了自定义文本框字段。现在我想要它(必修)。我通过传递参数" required" => true来尝试它。但它不起作用。请参阅以下代码

woocommerce_wp_text_input(
  array(
    'id' => 'special_price',
    'label' => __( 'Wholesaler Price *', 'woocommerce' ),
    'placeholder' => '',
    'desc_tip' => 'true',
    'required' => 'true',
    'description' => __( 'Enter wholesaler price here.', 'woocommerce' )
  )
);

但它不是强制使用文本框。请问任何人都可以告诉我该怎么做?

2 个答案:

答案 0 :(得分:6)

对于required HTML5属性和其他自定义属性woocommerce_wp_text_input(),函数具有custom_attributes选项。

woocommerce_wp_text_input(
  array(
    'id' => 'special_price',
    'label' => __( 'Wholesaler Price *', 'woocommerce' ),
    'placeholder' => '',
    'desc_tip' => 'true',
    'custom_attributes' => array( 'required' => 'required' ),
    'description' => __( 'Enter wholesaler price here.', 'woocommerce' )
  )
);

答案 1 :(得分:0)

您可以根据需要修改以下代码。

// Validate when adding to cart
        add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_to_cart_validation_custom', 10, 3 );

/  validation

    function woocommerce_add_to_cart_validation_custom($passed, $product_id, $qty){

        global $woocommerce;

$option = ''; // your custom field's name

   if( isset($_POST[sanitize_title($option)]) && $_POST[sanitize_title($option)] == '' )
        $passed = false;

    if (!$passed)
        $woocommerce->add_error( sprintf( __('"%s" is a required field.', 'woocommerce'), $option) );

        return $passed;

    }

如果在购物车中添加产品时有更多选项,您可能会发现How to add a custom text box value to cart session array in Woocommerce我的回答很有帮助。