Here’s how you can make a custom input field required in WooCommerce:

  1. Add the custom field to the product page: You need to add the custom field to the product page first, using WooCommerce’s actions and filters. You can do this by using the woocommerce_before_add_to_cart_button action and the woocommerce_form_field function.
  2. Add validation for the custom field: You can use the woocommerce_add_to_cart_validation filter to validate the custom field when a user adds the product to their cart. In the validation function, you can check if the custom field has a value and return an error if it doesn’t.

Here’s an example of code that adds a custom input field and makes it required:

add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_field_to_product' );
function add_custom_field_to_product() {
    echo '<div class="custom-field-container">';
    woocommerce_form_field( 'custom_field', array(
        'type'          => 'text',
        'class'         => array('custom-field form-row-wide'),
        'label'         => __('Custom Field'),
        'required'      => true,
    ), '' );
    echo '</div>';
}

add_filter( 'woocommerce_add_to_cart_validation', 'validate_custom_field', 10, 3 );
function validate_custom_field( $passed, $product_id, $quantity ) {
    if ( empty( $_POST['custom_field'] ) ) {
        wc_add_notice( __( 'Please enter a value for the custom field.' ), 'error' );
        $passed = false;
    }
    return $passed;
}

This code will add a custom input field labeled “Custom Field” to the product page and make it required. If a user tries to add the product to their cart without filling in the custom field, they will receive an error message.

(Visited 81 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window